我在結束一組動態創建的線程時遇到了一些麻煩。我需要在任何特定點結束所有這些的原因是,我可以刷新表單的某些部分並創建新表單。這裏有一個簡單的場景來展示我的線程發生了什麼。你如何加入/中止一組動態創建的線程?
多個線程被創建動態地基於就地某些變量:
for (int i = 0; i <= mDevices.Count; i++)
{
ThreadStart workerThread = delegate { pollDevices(mDevices[i - 2], this); };
new Thread(workerThread).Start();
}
public void pollDevices(IDeviceInterface device, DeviceManager mainUI)
{
System.Timers.Timer timer = null;
if (timer == null)
{
timer = new System.Timers.Timer(1000);
timer.Elapsed += delegate(object sender, ElapsedEventArgs e) { timerElapsed(sender, e, device, mainUI); };
}
timer.Enabled = true;
public void timerElapsed(object sender, ElapsedEventArgs e, IDeviceInterface device, DeviceManager mainUI)
{
device.connect(device, this);
//wait till thread finishes and destroy
Thread.CurrentThread.Abort();
}
這些線程然後工作過計時器,和PROC一個事件,它處理UI更新和這樣。然而,當我嘗試刷新用戶界面(例如,如果有更多的數據庫中的條目需要考慮)我從窗體上刪除按鈕(這些都分配給一個線程),如果一個線程仍然運行,我呼籲刷新我需要以這種方式停止所有當前線程。
所以我的問題是,我如何中止這組線程之前我刷新我的用戶界面?
猜想我需要重新思考某些事情之後,我繼續前進......有什麼指針/我應該首先查找的東西? –