返回Task.Factory.StartNew(()=> {;})是不正确的?

时间:2012-12-17 22:35:26

标签: c# c#-4.0 asynchronous task-parallel-library

这是我一直看到的代码 -

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(() => { ; });
    }

当您实际上不打算运行异步操作时,是否有更好的方法可以返回?或者你必须返回一个新的,启动的任务?是否有性能影响?

3 个答案:

答案 0 :(得分:8)

如果您使用.Net 4.5

,则可以使用Task.FromResult<T>
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();

答案 1 :(得分:1)

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

答案 2 :(得分: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
}