when I was playing with tasks on C#, I was wondering what's the difference between using GetAwaiter().OnCompleted() and callbacks
Case 1 : task1.GetAwaiter().OnCompleted()
Task task1 = new Task(() =>
{
//Do Work_1 here
});
task1.GetAwaiter().OnCompleted(() =>
{
//Do something here where Work_1 Completed
});
task1.Start();
Case 2 : CallBack
await Task2(() =>
{
//CallBack
});
private async Task Task2(Action callBack)
{
//do Work_2 here
await Task.Run(callBack);
}
I want to understand this and I think I'm missing something.
The async/await approach in C# is great in part because it isolates the asynchronous concept of waiting from other details. So when you await a predefined method in a third-party library or in . NET itself, you don't necessarily have to concern yourself with the nature of the operation you're awaiting.
C# Language Async-Await Returning a Task without awaitMethods that perform asynchronous operations don't need to use await if: There is only one asynchronous call inside the method. The asynchronous call is at the end of the method. Catching/handling exception that may happen within the Task is not necessary.
An async method returns to the caller as soon as the first await is hit (that operates on a non-completed task). So if that first execution "streak" of an async method takes a long time Task. Run will alter behavior: It will cause the method to immediately return and execute that first "streak" on the thread-pool.
Before discussing the differences, I have to point out one thing: you shoudn't use either of the two approaches. GetAwaiter()
is used internally by await
and it can be useful in some specialized code, but you shouldn't use it in normal code. And continuation actions are exactly what async
-await
is trying to avoid.
If you want to have a continuation, either use await
, or possibly ContinueWith()
. Both have the advantage that they are composable: the callee just returns a Task
and it's upon the caller to decide what to do it with it.
With that being said, there are some differences:
Task
fails.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