我有下一个代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在private void Window_Closing中进行代码工作,只有当它知道ProcessThread仍然是Alive/InProgress/running时.
类似于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;
}
}
}
Run Code Online (Sandbox Code Playgroud)