Threads spun with Task.Run always exit with exit code 259

c#, multithreading, task-parallel-library, wpf

Solution

Task.Run does not create a thread. It schedules a delegate to run on a ThreadPool thread. The threads in a threadpool are created or destroyed according to the CPU load.

The exit code you see has nothing really to do with your code: it may simply be a Visual Studio debug message, or a ThreadPool thread that exited.

Additionally, `async` doesn't mean that a method will run asynchronously. It is syntactic sugar that allows the compiler to create code to wait asynchronously for any asynchronous methods marked with `await`. In your case, `DoOnThread` has no asynchronous calls or `await` so it will run syncrhonously.

In fact, the compiler will even emit a warning that `DoOnThread` doesn't contain `await` so it will run synchronously

Problem

As a simple example I have a WPF application with a single button on the Main Window and code behind thus: ``` public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } async void Button_Click(object sender, RoutedEventArgs e) { await Task<bool>.Run(() => this.DoOnThread()); } async Task<bool> DoOnThread() { Thread.CurrentThread.Name = "MyTestThread"; Thread.Sleep(1000); return true; } } ``` If I break at "return true" via VisualStudio threads window I can get the ThreadID, if I continue and let the code run to completion and wait a little till the thread exits, I get "The thread 0x9ad34 has exited with code 259 (0x103)" displayed in the VS output window. What am I doing wrong and how do I ensure I get a thread exit code of 0?

Original source

Related problems