现实生活中的场景,使用TaskCompletionSource&LT; T&GT;? [英] Real life scenarios for using TaskCompletionSource<T>?
问题描述
我有困难的理解:在什么情况下会 TaskCompletionSource
AFAIK,它只知道,在某些时候,它的的setResult
或 SetException
方法被调用来完成在任务&LT; T&GT;
通过暴露了其工作
属性
在换句话说,它作为生产者的任务&LT; TResult&GT;
及其完成
我看到 此处 的例如:
如果我需要一种方法来执行函数功能异步,有一个任务 重新present该操作。
公共静态任务&LT; T&GT; RunAsync&LT; T&GT;(Func键&LT; T&GT;功能)
{
如果(函数== NULL)抛出新ArgumentNullException(功能);
VAR TCS =新TaskCompletionSource&LT; T&GT;();
ThreadPool.QueueUserWorkItem(_ =&GT;
{
尝试
{
牛逼的结果=()的函数;
tcs.SetResult(结果);
}
赶上(例外EXC){tcs.SetException(极好); }
});
返回tcs.Task;
}
可以用来如果我没有 Task.Factory.StartNew
但我的做有 Task.Factory.StartNew
有人可以通过例子来说明这是有关的直接到 TaskCompletionSource
的场景
而不是的假设的中,我没有的情况 Task.Factory.StartNew
?
我一直都用它的时候只是一个基于事件的API可(<一href="http://$c$c.msdn.microsoft.com/Windows-Phone-8-Networking-835239c1/source$c$c?fileId=70769&pathId=221052408">for例如,Windows Phone的8插槽的):
公共任务&LT;参数数量&GT; SomeApiWrapper()
{
TaskCompletionSource&LT;参数数量&GT; TCS =新TaskCompletionSource&LT;参数数量&GT;();
VAR OBJ =新SomeApi();
//将得到提高,当工作完成
obj.Done + =(参数)=&GT;
{
//这会通知主叫
//该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;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!