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?
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();
You could always just create a TaskCompletionSource and then return the Task property. This is a way to essentially skip the async call altogether.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With