Difference between Task Callbacks and OnCompleted()
Asked Answered
M

1

6

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.

Miscellanea answered 25/12, 2013 at 12:14 Comment(1)
One observation I have is the MSDN remark on the GetAwaiter() method: This method is intended for compiler user rather than use directly in code.Carrell
H
6

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.
Hadria answered 25/12, 2013 at 13:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.