我有困难的理解:在什么情况下会 TaskCompletionSource
AFAIK,它只知道,在某些时候,它的的setResult 或 SetException 方法被调用来完成在任务< T> 通过暴露了其工作属性
在换句话说,它作为生产者的任务< TResult> 及其完成
我看到 此处 的例如:
如果我需要一种方法来执行函数功能异步,有一个任务 重新present该操作。
公共静态任务< T> RunAsync< T>(Func键< T>功能) { 如果(函数== NULL)抛出新ArgumentNullException(功能); VAR TCS =新TaskCompletionSource< T>(); ThreadPool.QueueUserWorkItem(_ => { 尝试 { 牛逼的结果=()的函数; tcs.SetResult(结果); } 赶上(例外EXC){tcs.SetException(极好); } }); 返回tcs.Task; }
可以用来如果我没有 Task.Factory.StartNew
但我的做有 Task.Factory.StartNew
有人可以通过例子来说明这是有关的直接到 TaskCompletionSource 的场景 而不是的假设的中,我没有的情况 Task.Factory.StartNew ?
解决方案我一直都用它的时候只是一个基于事件的API可(for例如,Windows Phone的8插槽的):
公共任务<参数数量> SomeApiWrapper() { TaskCompletionSource<参数数量> TCS =新TaskCompletionSource<参数数量>(); VAR OBJ =新SomeApi(); //将得到提高,当工作完成 obj.Done + =(参数)=> { //这会通知主叫 //该SomeApiWrapper那 //任务刚刚完成 tcs.SetResult(参数); } //启动工作 obj.Do(); 返回tcs.Task; }
因此,当与C#一起使用,这是非常有用5 异步关键字。
I'm having difficulties understanding : In what scenarios would TaskCompletionSource?
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 asynchronously and have a Task 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
Can someone please explain by example a scenario which is related directly to TaskCompletionSource and not to hypothetical situation in which I don't have Task.Factory.StartNew ?
解决方案I mostly use it when only a 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.
更多推荐
现实生活中的场景,使用TaskCompletionSource&LT; T&GT;?
发布评论