Consider the case when you want your async task to return a value.
Existing synchronous method:
public int DoSomething()
{
return SomeMethodThatReturnsAnInt();
}
To make async, add async keyword and change return type:
public async Task<int> DoSomething()
To use Task.Factory.StartNew(), change the one-line body of the method to:
// start new task
var task = Task<int>.Factory.StartNew(
() => {
return SomeMethodThatReturnsAnInt();
},
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext() );
// await task, return control to calling method
await task;
// return task result
return task.Result;
vs. adding a single line if you use await Task.Yield()
// this returns control to the calling method
await Task.Yield();
// otherwise synchronous method scheduled for async execution by the
// TaskScheduler of the calling thread
return SomeMethodThatReturnsAnInt();
The latter is far more concise, readable, and really doesn't change the existing method much.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…