13,005
回編集
185行目: | 185行目: | ||
なお、キャンセル処理は<code>CancellationToken</code>構造体(<code>System.Threading</code>名前空間)を使用するが、上記の進捗表示より複雑になることに注意する。<br> | なお、キャンセル処理は<code>CancellationToken</code>構造体(<code>System.Threading</code>名前空間)を使用するが、上記の進捗表示より複雑になることに注意する。<br> | ||
<syntaxhighlight lang="c#"> | <syntaxhighlight lang="c#"> | ||
// 方法 1 | |||
private async void button2_Click(object sender, EventArgs e) | private async void button2_Click(object sender, EventArgs e) | ||
{ | { | ||
224行目: | 226行目: | ||
int percentage = i * 100 / n; // 進捗率 | int percentage = i * 100 / n; // 進捗率 | ||
progress.Report(percentage); | progress.Report(percentage); | ||
} | |||
return "全て完了"; | |||
} | |||
private void DisableAllButtons() | |||
{ | |||
button1.Enabled = false; | |||
button2.Enabled = false; | |||
} | |||
private void EableAllButtons() | |||
{ | |||
button1.Enabled = true; | |||
button2.Enabled = true; | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
<syntaxhighlight lang="c#"> | |||
// 方法 2 (Invokeメソッドの使用) | |||
private async void button2_Click(object sender, EventArgs e) | |||
{ | |||
DisableAllButtons(); | |||
toolStripStatusLabel1.Text = "処理中…"; | |||
toolStripProgressBar1.Value = 0; | |||
// 時間のかかる処理を別スレッドで開始 | |||
string result = await DoWorkAsync(100); | |||
// 処理結果の表示 | |||
toolStripStatusLabel1.Text = result; | |||
toolStripProgressBar1.Value = 100; | |||
MessageBox.Show("正常に完了"); | |||
EableAllButtons(); | |||
} | |||
// 時間のかかる処理を行うメソッド(進捗付き) | |||
private async Task<string> DoWorkAsync(int n) | |||
{ | |||
// 時間のかかる処理 | |||
for (int i = 1; i <= n; i++) | |||
{ | |||
await Task.Delay(100); | |||
int percentage = i * 100 / n; // 進捗率 | |||
// 進捗メッセージの変更 | |||
toolStripStatusLabel1.Invoke(new Action(() => | |||
{ | |||
toolStripStatusLabel1.Text = percentage + "% 完了"; | |||
})); | |||
// プログレスバーの進捗の変更 | |||
toolStripProgressBar1.Invoke(new Action(() => | |||
{ | |||
toolStripProgressBar1.Value = percentage; | |||
})); | |||
} | } | ||