退出代码为259线程

退出代码为259线程

本文介绍了纺与Task.Run始终退出,退出代码为259线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举一个简单的例子,我有在主窗口中的一个按钮和代码背后这样一个WPF应用程序:

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;
    }
}

如果我在打破通过VisualStudio的线程返回true窗户我能得到的ThreadID,如果我继续,让代码运行到完成并等待一点点,直到线程退出,我得到VS输出窗口中显示线程0x9ad34已与代码259(0x103)退出。

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.

我是什么做错了,我怎么保证我得到的0线程退出代码?

What am I doing wrong and how do I ensure I get a thread exit code of 0?

推荐答案

Task.Run做的的创建一个线程。它调度一个委托给一个线程池线程上运行。在一个线程池线程都根据CPU负荷创建或破坏。

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.

您看到的退出代码有没有真正与你的代码做的:它可能仅仅是一个Visual Studio调试信息,或退出一个线程池线程

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.

此外,异步并不意味着一个方法异步运行。这是语法糖,可以让编译器创建的代码以异步方式等待标记的异步方法等待。在你的情况, DoOnThread 没有异步调用或等待所以它将syncrhonously运行。

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.

在事实上,编译器会发出连一个警告, DoOnThread 不包含的await 所以它会同步运行。

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

这篇关于纺与Task.Run始终退出,退出代码为259线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:23