G-M*_*Man 17 c# multithreading
我想从我的.NET应用程序启动x个线程,我想跟踪它们,因为我需要手动终止它们,或者我的应用程序稍后关闭我的应用程序.
示例==>启动线程Alpha,启动线程测试..然后在我的应用程序中的任何点我应该能够说Terminate Thread Beta ..
跟踪.NET中打开的线程的最佳方法是什么?关于终止它的线程我需要知道什么(一个id?)?示例代码,教程会很有帮助.
Chr*_*s S 15
你可以节省自己的驴工作并使用这个智能线程池.它提供了一个工作单元系统,允许您在任何时候查询每个线程的状态,并终止它们.
如果这太麻烦了,那么提到的IDictionary<string,Thread>可能是最简单的解决方案.或者甚至更简单的是给你的每个线程一个名字,并使用IList<Thread>:
public class MyThreadPool
{
private IList<Thread> _threads;
private readonly int MAX_THREADS = 25;
public MyThreadPool()
{
_threads = new List<Thread>();
}
public void LaunchThreads()
{
for (int i = 0; i < MAX_THREADS;i++)
{
Thread thread = new Thread(ThreadEntry);
thread.IsBackground = true;
thread.Name = string.Format("MyThread{0}",i);
_threads.Add(thread);
thread.Start();
}
}
public void KillThread(int index)
{
string id = string.Format("MyThread{0}",index);
foreach (Thread thread in _threads)
{
if (thread.Name == id)
thread.Abort();
}
}
void ThreadEntry()
{
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以更多地参与其中并使其复杂化.如果杀死你的线程不是时间敏感的(例如,如果你不需要在UI中3秒内杀死一个线程),那么Thread.Join()是一种更好的做法.
如果您还没有阅读过,那么Jon Skeet 就SO上常见的"不要使用中止"建议进行了很好的讨论和解决方案.
| 归档时间: |
|
| 查看次数: |
41740 次 |
| 最近记录: |