動的に作成されたスレッドのグループを終了するのに問題があります。これらすべてを任意の時点で終了する必要がある理由は、フォームの特定の部分を更新して新しい部分を作成できるようにするためです。これが私のスレッドで何が起こるかを示す簡単なシナリオです。
いくつかのスレッドは、インプレースの特定の変数に基づいて動的に作成されます。
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();
}
次に、これらのスレッドはタイマーで動作し、UIの更新などを処理するイベントを処理します。ただし、UIを更新しようとすると(たとえば、データベース内のエントリをさらに考慮する必要がある場合)、スレッドがまだ実行されている場合、フォーム上のボタン(これらはスレッドに割り当てられています)を削除するとエラーが発生します。この方法で現在のすべてのスレッドを停止する必要がある更新を要求します。
だから私の質問は、UIを更新する前にこのスレッドのグループを中止するにはどうすればよいですか?