BackgroundWorker
コントロールだけの別のスレッドを使用することを検討できます。このように、Thread.Sleep()
メソッドを使用でき、アプリケーションの GUI が応答しなくなることはありません。詳細については、msdn: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspxを参照してください。
BackgroundWorker
コントロールをフォームに追加し、次のコードを使用して適切なイベントを処理します。
private void timer1_Tick(object sender, EventArgs e)
{
string[] DF_Engines = { Form2.Engine1, Form2.Engine2, Form2.Engine3, Form2.Engine4, Form2.Engine5, Form2.Engine6 };
//disable timer1, so it wont tick again until the current work is finished
timer1.Stop();
//start processing asynchronously, so GUI is still responsive
sampleBackgroundWorker.RunWorkerAsync(DF_Engines);
}
//this method should be attached to DoWork event of the BackgroundWorker
private void sampleBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string[] DF_Engines = (e.Argument as string[]);
foreach (string DF_Engine in DF_Engines)
{
if (Convert.ToDouble(DF_Engine) != 99)
{
string Hex_ADD1 = "{" + DF_Engine + "|";
Console.WriteLine(Hex_ADD1);
serialPort1.Write(Hex_ADD1);
//n gets overwritten in each iteration, is this line required?
n = Convert.ToInt16(DF_Engine);
Thread.Sleep(500);
}
}
//you can also pass a result from this method back to the GUI thread like this
//e.Result = "job done";
//this can be read later in RunWorkerCompleted method of the BackgroundWorker
}
//this method should be attached to RunWorkerCompleted event of the BackgroundWorker
private void sampleBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//start timer1, so it can invoke the worker again
timer1.Start();
}
これについてさらにサポートが必要な場合は、お知らせください。