Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Task Callbacks and OnCompleted()

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.

like image 831
AymenDaoudi Avatar asked Dec 25 '13 12:12

AymenDaoudi


People also ask

What is await Task run C#?

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.

Can we use async without await C#?

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.

How do you use await inside Task run?

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.


1 Answers

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:

  • In case 1, the continuation will run even when the Task fails.
  • In case 1, the continuation will run on the current synchronization context, if any. In case 2, the continuation will always run on a thread pool thread.
like image 64
svick Avatar answered Nov 15 '22 03:11

svick