c#如何访问我的线程?

c#如何访问我的线程?,c#,multithreading,C#,Multithreading,我有下一个代码: private void button_Click(object sender, RoutedEventArgs e) { Thread t = new Thread(Process); t.SetApartmentState(ApartmentState.STA); t.Name = "ProcessThread"; t.Start(); } private void Window_Closin

我有下一个代码:

private void button_Click(object sender, RoutedEventArgs e)
    {
        Thread t = new Thread(Process);
        t.SetApartmentState(ApartmentState.STA);
        t.Name = "ProcessThread";
        t.Start();
    }

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        string msg = "Really close?";
        MessageBoxResult result =
          MessageBox.Show(
            msg,
            "Closing",
            MessageBoxButton.YesNo,
            MessageBoxImage.Warning);
        if (result == MessageBoxResult.No)
        {
            e.Cancel = true;
        }
    }
只有当它知道ProcessThread仍然处于活动状态/InProgress/running时,我才需要在私有的void窗口中执行代码关闭

类似于IF(GetThreadByName(“ProcessThread”).IsAlive==true)


如何用C#编写它?

将线程声明为类中的成员变量:

public class MyForm : Form
{
   Thread _thread;

    private void button_Click(object sender, RoutedEventArgs e)
    {
        _thread = new Thread(Process);
        _thread.SetApartmentState(ApartmentState.STA);
        _thread.Name = "ProcessThread";
        _thread.Start();
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {

        if (_thread.IsAlive)
            //....

        string msg = "Really close?";
        MessageBoxResult result =
          MessageBox.Show(
            msg,
            "Closing",
            MessageBoxButton.YesNo,
            MessageBoxImage.Warning);
        if (result == MessageBoxResult.No)
        {
            e.Cancel = true;
        }
    }
}

查看System.Diagnostics.Process.GetProcessByName()。
您还可以遍历System.Diagnostics.Process.GetProcesses()来查找线程

或者你可以把你的线程放在你的类的全局范围内,这样你就可以从那里访问它


注意:我建议您在您创建的所有线程上使用.IsBackround=true,这样,胭脂线程不会阻止您的应用程序正常退出。:)

一种方法是声明一个成员变量,该变量指定后台线程是否正在运行。当线程启动时,可以将变量设置为true,然后在线程完成工作时将其设置为false

调用Window_Closing时,可以检查变量以查看线程是否已完成

您应该将变量声明为volatile,因为某些编译器/运行时优化可能会阻止此方法正常工作:

private volatile bool workerThreadRunning = false;

你是说,我还活着?另外,您可能希望在访问它之前检查_-thread是否为null。我并没有试图编写防弹和精确的代码,而是以一种清晰的方式说明他如何解决它。然后由OP 2编写实际的生产代码。