1、创建ThreadManager类
public class ThreadManager
{
private Dictionary<int, Thread> threadDict = new Dictionary<int, Thread>();
public void AddThread(Thread thread)
{
int threadId = thread.ManagedThreadId;
lock (threadDict)
{
if (!threadDict.ContainsKey(threadId))
{
threadDict.Add(threadId, thread);
}
}
}
public void RemoveThread(Thread thread)
{
int threadId = thread.ManagedThreadId;
lock (threadDict)
{
threadDict.Remove(threadId);
}
}
public Thread GetThreadById(int threadId)
{
lock (threadDict)
{
threadDict.TryGetValue(threadId, out Thread thread);
return thread;
}
}
public IEnumerable<int> GetThreadIds()
{
lock (threadDict)
{
return threadDict.Keys;
}
}
}
2、比如说现在创建了一个线程名为weight线程
? public Thread weight= new Thread(() => { });
#region 结束线程
public void AbortAllThreadsExceptMain()
{
// 创建一个线程管理器
ThreadManager threadManager = new ThreadManager();
// 获取主线程对象
Thread mainThread = Thread.CurrentThread;
int mainThreadId = mainThread.ManagedThreadId;
// 遍历当前进程中的所有线程,将线程添加到管理器中
foreach (ProcessThread processThread in Process.GetCurrentProcess().Threads)
{
int threadId = processThread.Id;
if (threadId != mainThreadId)
{
Thread thread = new Thread(() =>
{
// 线程的具体逻辑
Thread.Sleep(5000);
});
threadManager.AddThread(thread);
}
}
// 在需要结束 weight 线程时,获取该线程对象并终止线程
Thread weightProcessThread = threadManager.GetThreadById(weight.ManagedThreadId);
if (weightProcessThread != null)
{
weightProcessThread.Abort();
threadManager.RemoveThread(weightProcessThread);
}
// 在需要结束其他线程时,通过线程管理器获取线程对象并终止线程
foreach (int threadId in threadManager.GetThreadIds())
{
Thread thread = threadManager.GetThreadById(threadId);
if (thread != null && thread != weightProcessThread)
{
thread.Abort();
}
}
// 等待所有线程结束
foreach (int threadId in threadManager.GetThreadIds())
{
Thread thread = threadManager.GetThreadById(threadId);
thread?.Join();
}
Console.WriteLine("所有线程已结束");
}
#endregion
3、结束线程方法的使用
//检测线程是否使用
//第一种
if (weight.IsAlive)
{
try
{
AbortAllThreadsExceptMain();
}
catch (Exception)
{
}
}
//第二种
if (weight_process_thread.ThreadState == ThreadState.Running)
{
try
{
AbortAllThreadsExceptMain();
}
catch (Exception)
{
}
}