5

这是我一直看到的代码-

public Task PossiblyAsyncOperation(bool condition)
    {
        //this condition means i need to do something async, for sure
        if (condition)
             return AsyncOp();

        //since it didnt hit the above condition
        //we're not doing the async op now
        //.....this just feels wrong
        return Task.Factory.StartNew(() => { ; });
    }

当您实际上不打算最终运行异步操作时,是否有更好的返回方式?还是您必须返回一个新的、已开始的任务?这对性能有影响吗?

4

3 回答 3

8

Task.FromResult<T> 如果您使用的是 .Net 4.5,则可以使用

return Task.FromResult<object>(null);

否则你可以编写自己的实现

public static Task CreateEmptyTask()
{
    var tcs = new TaskCompletionSource<object>();
    tsc.SetResult(null);
    return tcs.Task;
}

正如评论指出的那样,您也许可以缓存此任务,但请注意您必须防止它被处置。例如以下将引发异常:

public static readonly Task EmptyTask = Task.FromResult<object>(null);

Task t = EmptyTask;
t.Dispose();
((IAsyncResult)t).AsyncWaitHandle.WaitOne();
于 2012-12-17T22:47:21.570 回答
1

您总是可以只创建一个TaskCompletionSource,然后返回 Task 属性。这是一种完全跳过异步调用的方法。

于 2012-12-17T22:36:51.507 回答
0

如果你什么都没做,而且Task是一个类,所以一个引用,为什么不简单地返回一个null..

public Task PossiblyAsyncOperation(bool condition)
{
     //this condition means i need to do something async, for sure
     if (condition)
          return AsyncOp();

     //since it didnt hit the above condition
     //we're not doing the async op now
     //.....this just feels wrong
     return null; //RETURN NULL
}
于 2012-12-17T22:38:13.680 回答