wpf 用 Task.Run 旋转的线程总是以退出代码 259 退出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21632584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Threads spun with Task.Run always exit with exit code 259
提问by John
As a simple example I have a WPF application with a single button on the Main Window and code behind thus:
作为一个简单的例子,我有一个 WPF 应用程序,主窗口上有一个按钮,代码如下:
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.
如果我通过 VisualStudio 线程窗口在“返回真”处中断,我可以获得 ThreadID,如果我继续并让代码运行完成并稍等片刻直到线程退出,我会得到“线程 0x9ad34 已退出,代码为 259 (0x103 )”显示在 VS 输出窗口中。
What am I doing wrong and how do I ensure I get a thread exit code of 0?
我做错了什么,如何确保线程退出代码为 0?
回答by Panagiotis Kanavos
Task.Run does notcreate 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.
Task.Run并没有创建一个线程。它安排一个委托在 ThreadPool 线程上运行。线程池中的线程根据 CPU 负载创建或销毁。
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.
您看到的退出代码与您的代码没有任何关系:它可能只是一条 Visual Studio 调试消息,或者一个退出的 ThreadPool 线程。
Additionally, asyncdoesn'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, DoOnThreadhas no asynchronous calls or awaitso it will run syncrhonously.
此外,async并不意味着方法将异步运行。它是一种语法糖,允许编译器创建代码以异步等待任何标记为 的异步方法await。在您的情况下,DoOnThread没有异步调用,await因此它将同步运行。
In fact, the compiler will even emit a warning that DoOnThreaddoesn't contain awaitso it will run synchronously
事实上,编译器甚至会发出一个DoOnThread不包含的警告,await所以它会同步运行
回答by Stephen Cleary
Thread pool threads do not belong to you. You should not set their Name, nor should you be concerned about their exit codes.
线程池线程不属于你。您不应该设置他们的Name,也不应该关心他们的退出代码。

