创建完成的任务&LT; T&GT; [英] Create a completed Task<T>
本文介绍了创建完成的任务&LT; T&GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我采取的方法任务&LT;结果&GT; StartSomeTask()
键,碰巧知道该方法被调用之前已经结果。如何创建一个任务&LT; T&GT; 一个已经完成了
这就是我正在做的:
私人只读结果theResult =新的结果();
公众覆盖任务&LT;结果&GT; StartSomeTask()
{
VAR任务=新的任务和LT;结果&GT;(()=&GT; theResult);
task.RunSynchronously(CurrentThreadTaskScheduler.CurrentThread);
返回任务;
}
有没有更好的解决办法?
解决方案
私人只读结果theResult =新的结果();
公众覆盖任务&LT;结果&GT; StartSomeTask()
{
VAR taskSource =新TaskCompletionSource&LT;结果&GT;();
taskSource.SetResult(theResult);
返回taskSource.Task;
}
I'm implementing a method Task<Result> StartSomeTask()
and happen to know the result already before the method is called. How do I create a Task<T> that has already completed?
This is what I'm currently doing:
private readonly Result theResult = new Result();
public override Task<Result> StartSomeTask()
{
var task = new Task<Result>(() => theResult);
task.RunSynchronously(CurrentThreadTaskScheduler.CurrentThread);
return task;
}
Is there a better solution?
解决方案
private readonly Result theResult = new Result();
public override Task<Result> StartSomeTask()
{
var taskSource = new TaskCompletionSource<Result>();
taskSource.SetResult(theResult);
return taskSource.Task;
}
这篇关于创建完成的任务&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文