How could I convert the method:
static void DoWork(Action<bool> onCompleteCallback)
{
Task doWork = new Task( ()=>Thread.Sleep(2000) );
Action<Task> onComplete = (task) => {
onCompleteCallback(true); // should execute on the main thread
};
doWork.ContinueWith(onComplete, TaskScheduler.FromCurrentSynchronizationContext());
doWork.Start();
}
to Async.
If I convert it to Async what will be the difference?
Part of the reason to use
asyncandawaitis to avoid callbacks. By using the newasyncsupport, your method itself can return aTask(orTask<T>), and you can just useawaiton it, avoiding the need to pass in a callback entirely.If you wanted to use the new async/await setup, you’d write this as:
The difference would actually be in how you call this. Instead of using a callback, you’d just write:
You could, of course, pass the callback in still, and write it as:
This just defeats the purpose (somewhat) of using the new support, as one of the main advantages is that you no longer need to pass around callbacks and turn your logic “inside-out”.