据我所知,它只知道在某个时候,它的 SetResult
或 SetException
正在调用方法来完成 Task<T>
通过其 Task
暴露属性(property)。
换句话说,它充当 Task<TResult>
的生产者及其完成。
我看到了here示例:
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
.
问题:
有人可以举例说明直接与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/