c# - 什么时候应该使用 TaskCompletionSource<T>?

标签 c# .net .net-4.0 task-parallel-library taskcompletionsource

据我所知,它只知道在某个时候,它的 SetResultSetException正在调用方法来完成 Task<T>通过其 Task 暴露属性(property)。

换句话说,它充当 Task<TResult> 的生产者及其完成。

我看到了here示例:

If I need a way to execute a Func<T> asynchronously and have a Task<T> to represent that operation.

public static Task<T> RunAsync<T>(Func<T> function) 
{ 
    if (function == null) throw new ArgumentNullException(“function”); 
    var tcs = new TaskCompletionSource<T>(); 
    ThreadPool.QueueUserWorkItem(_ => 
    { 
        try 
        {  
            T result = function(); 
            tcs.SetResult(result);  
        } 
        catch(Exception exc) { tcs.SetException(exc); } 
    }); 
    return tcs.Task; 
}

如果我没有 Task.Factory.StartNew 就可以使用- 但我确实Task.Factory.StartNew .

问题:

有人可以举例说明直接TaskCompletionSource相关的场景吗? 而不是我没有 Task.Factory.StartNew假设情况?

最佳答案

我主要在只有基于事件的 API 可用时使用它(for example Windows Phone 8 sockets):

public Task<Args> SomeApiWrapper()
{
    TaskCompletionSource<Args> tcs = new TaskCompletionSource<Args>(); 

    var obj = new SomeApi();

    // will get raised, when the work is done
    obj.Done += (args) => 
    {
        // this will notify the caller 
        // of the SomeApiWrapper that 
        // the task just completed
        tcs.SetResult(args);
    }

    // start the work
    obj.Do();

    return tcs.Task;
}

所以当它与 C#5 async 关键字一起使用时特别有用。

关于c# - 什么时候应该使用 TaskCompletionSource<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316613/

相关文章:

c# - 使用扩展方法调用 WCF 服务

c# - C# 中 WinForm TextBox 中数字的按键事件

.net - 测试 TCP 端口是否在未连接的情况下打开

wpf - 在 WPF 中,您如何为多屏幕编写应用程序?

c# - 实时图形绘制(波形)

c# - C#中组合框的使用方法

c# - 如何使用 Reflection.Emit 调试在运行时生成的 IL 代码

asp.net - 从 System.IO.Stream 对象中查找文件扩展名

c# - 我在某处有隐藏的配置文件吗?

c# - 不寻常的异常行为?