我正在实现一个方法,Task<Result> StartSomeTask()并且碰巧在调用该方法之前已经知道了结果。如何创建已经完成的Task ?
Task<Result> StartSomeTask()
这是我目前正在做的:
private readonly Result theResult = new Result(); public override Task<Result> StartSomeTask() { var task = new Task<Result>(() => theResult); task.RunSynchronously(CurrentThreadTaskScheduler.CurrentThread); return task; }
有更好的解决方案吗?
private readonly Result theResult = new Result(); public override Task<Result> StartSomeTask() { var taskSource = new TaskCompletionSource<Result>(); taskSource.SetResult(theResult); return taskSource.Task; }