c#如何访问我的线程?

时间:2011-01-12 11:40:30

标签: 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_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;
        }
    }

我需要在private void Window_Closing中执行代码工作,只有当它知道ProcessThread仍然是Alive / InProgress / running ..

像IF(GetThreadByName(“ProcessThread”)。IsAlive == true)..

我将如何在C#中编写它?

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

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

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

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

private volatile bool workerThreadRunning = false;

答案 2 :(得分:0)

查看System.Diagnostics.Process.GetProcessesByName() 您还可以迭代System.Diagnostics.Process.GetProcesses()来查找您的主题。

或者你可以把你的主题放在你班级的全球范围内,这样你就可以从那里访问它。

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