C#
定石2: Task.Run + Control.Invokeでモダンに書く
出典: WinForms 非同期処理の正解 — BackgroundWorker / Task.Run / async-await の使い分け — 定石2: Task.Run + Control.Invokeでモダンに書く
// ✅定石2: Task.Run + Control.Invoke
using System.Threading.Tasks;
public partial class ImportForm : Form
{
private void btnStart_Click(object sender, EventArgs e)
{
Task.Run(()=> DoHeavyWork());
}
private void DoHeavyWork()
{
//バックグラウンドスレッドで動く(UI触れない)
for (int i = 0; i < 100; i++)
{
Thread.Sleep(50);
// UI更新はControl.Invokeでマーシャリング
int percent = i + 1;
this.BeginInvoke(new Action(()=>
{
progressBar1.Value = percent;
}));
}
//完了通知も同様
this.BeginInvoke(new Action(()=>
{
lblStatus.Text = "完了";
}));
}
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「定石2: Task.Run + Control.Invokeでモダンに書く」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
5 件// ✅定石1: BackgroundWorkerでファイル取り込み using System.ComponentModel; public partial class ImportForm : Form未収録
定石1: BackgroundWorker —旧式だがDesigner配置できる
#b0579a8291a4
// ✅定石3: async-await + Task.Run(新規プロジェクトの本命) using System.Threading.Tasks; public partial class ImportForm : Form未収録
定石3: async-await + Task.Run —新規プロジェクトの本命
#53f919be06e4
// ✅定石4: IProgress<T>で進捗報告(async-await版BackgroundWorker.ReportProgress) using System; using System.Threading.Tasks;未収録
定石4: IProgressで進捗をUIに細かく反映
#fa2904c0a651
// ✅定石5: CancellationTokenでキャンセル可能 using System.Threading; using System.Threading.Tasks;未収録
定石5: CancellationTokenでキャンセル可能にする
#298c9a3462f2
// ❌ NG: UIスレッドでWait()/ Resultを呼ぶとデッドロック private void btnStart_Click(object sender, EventArgs e) { var result = Task.Run(()=> DoHeavyWork()).Result; // ← UIスレッド固まる未収録
定石6: Wait()/ Resultでデッドロック—業務系の禁忌パターン
#8f703fd10c73
