Why thread in background is not waiting for task to complete?
async-await, c#
Solution
So, `BgDoWork` is called on a background thread by the `BackgroundWorker`
It calls `Method`, which starts the loop and calls `http.GetAsync`
`GetAsync` returns a `Task` and continues it's work on another thread.
You `await` the Task which, because the `Task` has not completed, returns from `Method`
Similarly, the await in `BgDoWork` returns another `Task`
So, the `BackgroundWorker` sees that `BgDoWork` has returned and assumes it has completed.
It then raises `RunWorkerCompleted`
Basically, don't mix `BackgroundWorker` with `async / await`!
Problem
I am playing with async await feature of C#. Things work as expected when I use it with UI thread. But when I use it in a non-UI thread it doesn't work as expected. Consider the code below ``` private void Click_Button(object sender, RoutedEventArgs e) { var bg = new BackgroundWorker(); bg.DoWork += BgDoWork; bg.RunWorkerCompleted += BgOnRunWorkerCompleted; bg.RunWorkerAsync(); } private void BgOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { } private async void BgDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { await Method(); } private static async Task Method() { for (int i = int.MinValue; i < int.MaxValue; i++) { var http = new HttpClient(); var tsk = await http.GetAsync("http://www.ebay.com"); } } ``` When I execute this code, background thread don't wait for long running task in `Method` to complete. Instead it instantly executes the `BgOnRunWorkerCompleted` after calling `Method`. Why is that so? What am I missing here? P.S: I am not interested in alternate ways or correct ways of doing this. I want to know what is actually happening behind the scene in this case? Why is it not waiting?