2011-01-12 46 views
2

我有下面的代码:c#如何访问我的线程?

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

我需要做的代码工作在私人无效WINDOW_CLOSING只有当它知道那么ProcessThread还活着/ INPROGRESS /运行..

喜欢的东西IF( GetThreadByName(“ProcessThread”)。IsAlive == true)..

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

回答

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

太好了!这很简单,我很白痴:)谢谢! – DefinitionHigh 2011-01-12 12:07:18

0

看System.Diagnostics.Process.GetProcessesByName()。
您也可以遍历System.Diagnostics.Process.GetProcesses()来查找您的线程。

或者您可以将您的线程放在您班级的全球范围内,以便您可以从此处访问它。

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

1

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

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

您应变量声明为挥发,某些编译/运行的优化可以正常工作停止这种做法:

private volatile bool workerThreadRunning = false;