如何在c#中自动从线程列表中删除线程



从标题中可以清楚地看出,
当线程作业完成时,我希望自动从线程列表中删除线程
类似:

Thread thr;
if(thr.done)
{
threadlist.remove(thr);
}

您可以检查线程是否已使用IsAlive完成,并在计时器中调用此函数:

var _timer = new Timer();
_timer.Interval = 30*1000; // specify interval time as you want
_timer.Tick += new EventHandler(timer_Tick);
void timer_Tick(object sender, EventArgs e)
{
foreach (var thr in threadList)
{
if (!thr.IsAlive)
{
threadlist.Remove(thr);
}
}
}
_timer.Start();

更好的解决方案是在线程中使用tryfinally块来确定何时完成处理。参见此示例:

private static int lastThreadID=0;  //We assign an ID to each thread
protected static object _lock = new object();
var thread = new Thread((tID) =>
{
try
{
work();
}
finally
{
removeThread((int)tID );
}
});
lock (_lock)
{
threadlist.Add(Tuple.Create(++lastThreadID, thread));
}
thread.Start(lastThreadID);
Action work = () =>
{
for (int i = 0; i < 20; i++)
Thread.Sleep(1000);
};

private static void removeThread(int tID)
{
lock (_lock)
{
threadlist.RemoveAll((x) => x.Item1 == tID);
}
}

最新更新