Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it incorrect to return Task.Factory.StartNew( ()=>{ ; } )?

Here's the code i keep seeing--

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

Is there a better way to return when you're not actually going to end up running an async operation? Or do you have to return a new, started task? Is there a performance hit for that?

like image 324
Micah Avatar asked Dec 17 '12 22:12

Micah


2 Answers

You could use Task.FromResult<T> if you're using .Net 4.5

return Task.FromResult<object>(null);

Otherwise you could write your own implementation

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

As the comment points out, you may be able to cache this task, however beware that you must prevent it from being disposed. For example the following would throw an exception:

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

Task t = EmptyTask;
t.Dispose();
((IAsyncResult)t).AsyncWaitHandle.WaitOne();
like image 76
Lee Avatar answered Oct 13 '22 19:10

Lee


You could always just create a TaskCompletionSource and then return the Task property. This is a way to essentially skip the async call altogether.

like image 42
Davin Tryon Avatar answered Oct 13 '22 21:10

Davin Tryon