AFAIK, all it knows is that at some point, its SetResult or SetException method is being called to complete the Task<T> exposed through its Task property.

In other words, it acts as the producer for a Task<TResult> and its completion.

I saw here the example:

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; 
}

Which could be used if I didn’t have Task.Factory.StartNew - But I do have Task.Factory.StartNew.

Question:

Can someone please explain by example a scenario related directly to TaskCompletionSource and not to a hypothetical situation in which I don't have Task.Factory.StartNew?

推荐答案

I mostly use it when only an event based API is available (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;
}

So it's especially useful when used together with the C#5 async keyword.

.net相关问答推荐

.NET Blazor-使用子组件中的处理程序方法进行双向数据绑定

DI通过对象的接口而不是实际类型来解析服务

升级到.NET8后,SignalR(在坞站容器上)网关损坏

查询 MongoDb 中嵌入式文档中的一个字段,该字段抛出调用运算符的左侧必须是对持久属性的直接访问

.NET 中两个子字符串之间的非贪婪正则表达式匹配

在 .NET 中使用 AES 解密时缺少后半字节

Owin Twitter登录-根据验证程序远程证书无效

是否有用于 Windows / C# 开发的可嵌入 Webkit 组件?

有什么方法可以在不重新编译的情况下覆盖 .NET Windows 服务名称?

什么是 Hashtable 的通用版本?

如何使用 Android 使用 WCF 服务

从 Windows 窗体打开 URL

迭代器和枚举器的区别

如何将 WebResponse.GetResponseStream 返回转换为字符串?

有没有像样的 C# 分析器?

场与财产.性能优化

CI服务器的比较?

安装带有恢复操作的 Windows 服务以重新启动

使用 C# 将时间跨度值转换为格式hh:mm Am/Pm

如何卸载Microsoft .NET Core 1.0.0 RC2 - VS 2015 Tooling Preview 1?