Question

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.

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top