gpt4 book ai didi

c# - 启动多个线程并从我的 .NET 应用程序中跟踪它们

转载 作者:可可西里 更新时间:2023-11-01 02:59:23 24 4
gpt4 key购买 nike

我想从我的 .NET 应用程序启动 x 个线程,并且我想跟踪它们,因为我需要手动终止它们,或者当我的应用程序稍后关闭我的应用程序时。

示例 ==> Start Thread Alpha,Start Thread Beta .. 然后在我的应用程序中的任何时候我都应该能够说 Terminate Thread Beta ..

在 .NET 中跟踪打开的线程的最佳方法是什么?我需要了解有关终止线程的哪些信息(ID?)?

最佳答案

你可以节省自己的驴子工作并使用这个 Smart Thread Pool 。它提供了一个工作单元系统,允许您随时查询每个线程的状态,并终止它们。

如果这太麻烦了,那么如上所述 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()
{

}
}

当然,您可能会更加复杂。如果终止线程对时间不敏感(例如,如果您不需要在 UI 中的 3 秒内终止线程),那么 Thread.Join() 是更好的做法。

如果您还没有读过,那么 Jon Skeet 有 this good discussion and solution对于 SO 上常见的“不要使用中止”建议。

关于c# - 启动多个线程并从我的 .NET 应用程序中跟踪它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2356130/

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