TaskCompletionSource< T>何时应使用? [英] When should TaskCompletionSource<T> be used?
问题描述
AFAIK,它所知道的只是在某个时候,其 SetResult
或 SetException
方法被调用来完成通过其 Task
属性公开的 Task< T>
。
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.
换句话说,它充当 Task< TResult>
及其完成的生产者。
In other words, it acts as the producer for a Task<TResult>
and its completion.
I看到>在此处此处 示例:
如果我需要一种异步执行Func并有一个Task
表示该操作的方法。
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;
}
可以使用*如果我没有 Task.Factory.StartNew
-
但是我做有 Task.Factory.StartNew
。
Which could be used *if I didn’t have Task.Factory.StartNew
-
But I do have Task.Factory.StartNew
.
问题:
有人可以举例说明与直接相关的情况吗? 到 TaskCompletionSource
,而不是我没有 Task的假设情况.Factory.StartNew
?
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
?
推荐答案
当基于事件的API仅可用时,我通常会使用它( 例如Windows Phone 8套接字):
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;
}
因此与C#5 <$ c $一起使用时,它特别有用c> async 关键字。
So it's especially useful when used together with the C#5 async
keyword.
这篇关于TaskCompletionSource< T>何时应使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!