什么时候应该 TaskCompletionSource<T>使用? [英] When should TaskCompletionSource<T> be used?
问题描述
AFAIK,它只知道在某个时刻,它的 SetResult
或 SetException
方法被调用以完成 Task
通过其 Task
属性公开.
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
及其完成的生产者.
In other words, it acts as the producer for a Task<TResult>
and its completion.
我在这里看到了例子:
I saw here the example:
如果我需要一种方法来异步执行 Func
并有一个 Task
表示该操作.
If I need a way to execute a
Func<T>
asynchronously and have aTask<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
.
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 async
关键字一起使用时特别有用.
So it's especially useful when used together with the C#5 async
keyword.
这篇关于什么时候应该 TaskCompletionSource<T>使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!