gpt4 book ai didi

c# 如何访问我的线程?

转载 作者:行者123 更新时间:2023-12-03 19:44:55 24 4
gpt4 key购买 nike

我有下一个代码:

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 仍然处于事件状态/进行中/正在运行时,我才需要在 private void Window_Closing 中执行代码工作。

类似于 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;
}
}
}

关于c# 如何访问我的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4668343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com