获取正在运行的线程
如果我通过代码运行各种线程,
var t = new Thread(() =>
{
try
{
}
}
catch (Exception ca)
{
MessageBox.Show(ca.Message);
}
});
t.SetApartmentState(ApartmentState.STA);
t.Name = "Thread1";
t.Start()
我们可以得到一些东西,我们可以稍后通过知道其名称来终止线程,假设我们打算停止线程 1 或线程 4,我们应该能够停止它:)
if i run various threads by code
var t = new Thread(() =>
{
try
{
}
}
catch (Exception ca)
{
MessageBox.Show(ca.Message);
}
});
t.SetApartmentState(ApartmentState.STA);
t.Name = "Thread1";
t.Start()
can we have something that we can later on terminate the thread by knowing its name lets say we intend to stop thread1 or thread4 we should be able to stop it:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者,如果您有一个线程列表,并且每当创建新线程时,将其添加到列表中,并且定期删除已退出的线程,那就更简单了。您可能还需要同步。
Or it's simpler if you have a list of threads and whenever you create a new one, you add it to your list, and you regularly remove threads that have exited. You might also need synchronization.
如果你有一个像
Dictionary
这样的东西,那么事情会很容易,当你启动一个线程时,将它放入字典中,并以其名称作为键。然后你可以使用以下方法通过名称获取一些线程:Things will be quite easy if you have something like a
Dictionary<string,Thread>
, when you start a thread, put it in the dictionary with its name as the key. Then you can get some thread by its name using:Thread 类有一个 Abort 方法允许您终止线程。也就是说,终止线程的正确方法是使用一些共享资源来指示线程是否应该继续或停止。例如,在线程内部,您可以实现一种机制,在循环中测试此静态变量的值并跳出循环。在主线程上,当您决定终止后台线程时,只需设置静态变量的值,线程就会自行停止。
这是一个示例:
在线程内部:
当您决定从另一个线程停止该线程时:
The Thread class has an Abort method which allows you to terminate the thread. This being said the proper way to terminate a thread is to use some a shared resource which indicates whether the thread should continue or stop. For example inside the thread you could implement a mechanism which tests the value of this static variable in a loop and break out of the loop. On the main thread when you decide to terminate the background thread simply set the value of the static variable and the thread will simply stop by itself.
Here's an example:
and inside the thread:
and when you decide to stop the thread from another thread:
您可以构建一个
Dictionary
。键是名称,值是线程对象本身。然后,您可以对从字典获得的线程对象调用 Abort 方法。注意:中止并不是结束线程的好方法。尝试使用一些全局标志。
You could build a
Dictionary <string,Thread>
. The key is the name and the value is the thread object itself. You then call Abort method on the thread object obtained from the dicitonary.NOTE: Abort is not a very good way to end a thread. Try using some global flags.