我创建了一个线程,并想杀死他。我在Process.GetCurrentProcess().Threads
中找到了自己的线程,但是它具有ProcessThread
类,并且无法转换为Thread
,所以我无法杀死他。
foreach (Thread thread in currentProcess.Threads)//throw error:unable to cast
{
if (thread.ManagedThreadId.Equals(processThreadId))
{
thread.Abort();
}
}
答案 0 :(得分:0)
System.Diagnostics.ProcessThread与System.Threading.Thread的概念不同。
一种快速的解决方案是保存在ConcurrentBag中创建的所有任务
int processThreadId = 0;
var threads = new ConcurrentDictionary<int,Thread>();
///...Some action
var newThread = new Thread(()=> {});
newThread.Start();
threads.TryAdd(newThread.ManagedThreadId,newThread);
///...Some action
Thread thread = null;
if(threads.TryRemove(processThreadId,out thread)){
thread.Abort();
}
似乎可以将ManagedThreadId转换为NativeThreadId 有关更多信息,Getting the thread ID from a thread