如果主線程完成,我需要清理每個正在運行的線程。在啓動之後,我立即將正在運行的線程放入List<Thread>
集合中。 我的「車輪」的方法是:是否有任何方便的方法來定期檢查線程狀態?
static void CheckThreadIsAliveJob(object thread)
{
while (((Thread)thread).IsAlive)
{
Thread.Sleep(1000);
}
// DO staff
}
我覺得我的做法是對的線程大量非常昂貴的,因爲我需要與CheckThreadIsAliveJob
身體開始新的線程爲每個人。
任何想法?
我rewrited上面的代碼,但是這看起來還是AGLY:
static void RemoveFinishedThreadsJob(object threadList)
{
foreach (var thread in (IList<Thread>)threadList)
{
if (!thread.IsAlive)
lock (threadList)
{
((IList<Thread>) threadList).Remove(thread);
}
}
Thread.Sleep(1000);
}
我實現了IDisposable接口的Dispose方法在我的課:
public void Dispose()
{
foreach (var thread in _runningThreads)
{
if (thread.IsAlive)
thread.Abort();
if (_removeFinishedThreads.IsAlive)
_removeFinishedThreads.Abort();
}
}
現在,當應用程序被關閉和GC正在收集垃圾,所有正在運行的線程都將手動中止。
您正在重新實現Thread.IsBackground屬性。只需將其設置爲* true *。 – 2015-03-13 11:18:06