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

Mic*_*cah 5 c# asynchronous task-parallel-library c#-4.0

这是我一直看到的代码 -

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(() => { ; });
    }
Run Code Online (Sandbox Code Playgroud)

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

Lee*_*Lee 8

你可以使用Task.FromResult<T> ,如果你正在使用.NET 4.5

return Task.FromResult<object>(null);
Run Code Online (Sandbox Code Playgroud)

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

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

正如评论指出的那样,您可以缓存此任务,但要注意必须防止它被处置.例如,以下内容将抛出异常:

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

Task t = EmptyTask;
t.Dispose();
((IAsyncResult)t).AsyncWaitHandle.WaitOne();
Run Code Online (Sandbox Code Playgroud)