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.5Otherwise you could write your own implementation
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: