私は Web 開発者で、マルチスレッド プログラミングに取り組もうとしています。あるフォームでは、非同期デリゲートを使用して、2 番目のスレッドで値を計算するメソッドを実行しようとしています。また、UI スレッドの実際の進行状況を示すプログレス バーが通知されることも必要です。
delegate void ShowProgressDelegate(int total, int value);
delegate void ComputeDelegate(int value);
//Some method simulating sophisticated computing process
private void Compute(int value)
{
ShowProgress(value, 0);
for (int i = 0; i <= value; i++)
{
ShowProgress(value, i);
}
}
//Method returning values into UI thread
private void ShowProgress(int total, int value)
{
if (!this.InvokeRequired)
{
ComputeButton.Text = value.ToString();
ProgressBar.Maximum = total;
ProgressBar.Value = value;
}
else
{
ShowProgressDelegate showDel = new ShowProgressDelegate(ShowProgress);
this.BeginInvoke(showDel, new object[] { total, value });
}
}
//firing all process
private void ComputeButton_Click(object sender, EventArgs e)
{
ComputeButton.Text = "0";
ComputeDelegate compDel = new ComputeDelegate(Compute);
compDel.BeginInvoke(100000, null, null);
}
これを実行すると、UIスレッドでまだ実行されていることを除いて、すべてが問題なく計算されます(フォームのボタンをクリックするとフリーズするためだと思います)。
なんで?同じコードでビルド可能なサンプル プロジェクト (VS2010) も添付します: http://osmera.com/windowsformsapplication1.zip
初心者を助けてくれてありがとう。