0

I have a code like this:

var t = new Thread(async () =>
    {
        await DoSomeWorkAsync();
    });
t.Start();
t.Join();


..

public static async Task DoSomeWorkAsync()
{
    var o = await GetSomethingAsync();
    o.StartSomething();
    ..
}

I've noticed that the t.Join() returns automatically after the await. I'd like to understand why.

Thanks

0x8000FFFF
  • 39
  • 4
  • _The_ fundamental characteristic of `async` methods is that such a method will _return_ on reaching the first `await` statement which cannot be completed synchronously. Since a thread exits when its entry point method returns, _that ends the thread_. Any investigation at all into what `async`/`await` does would have revealed that. See duplicates for discussions address this directly and more generally. – Peter Duniho Nov 02 '20 at 05:30
  • Related: [Is it ok to use “async” with a ThreadStart method?](https://stackoverflow.com/questions/44364092/is-it-ok-to-use-async-with-a-threadstart-method) – Theodor Zoulias Nov 02 '20 at 12:20

1 Answers1

0
I'd like to understand why

Because the constructor you are using has delegate with a void return type, you will see the same behaviour with other delegates of the same nature, like actions.

public delegate void ThreadStart();

The compiler would warn you about this. However, in short you are running the async lambda task completely unobserved regardless of the thread you started.

FWIW, you should steer away from the Thread class altogether and use Tasks (unless you have an exceptional use case that would specifically require it).

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • Thanks! That makes sense. I thought adding an async lambda will make the thread await. I tried adding a line after the await and that code never get executed: var t = new Thread(async () => { await DoSomeWorkAsync(); DoSomethingSync(); }); I expected DoSomethingSync to be executed at least. – 0x8000FFFF Nov 02 '20 at 05:05
  • @0x8000FFFF Yeah there are several things going on here, all of them bad.. In short, don't do that :) – TheGeneral Nov 02 '20 at 05:12
  • @0x8000FFFF Also the reason its not running the subsequent methods is because your application is likely ending before it schedules the continuation to the *antecedent* task – TheGeneral Nov 02 '20 at 05:22