C#
定石1: BackgroundWorker —旧式だがDesigner配置できる
出典: WinForms 非同期処理の正解 — BackgroundWorker / Task.Run / async-await の使い分け — 定石1: BackgroundWorker —旧式だがDesigner配置できる
// ✅定石1: BackgroundWorkerでファイル取り込み
using System.ComponentModel;
public partial class ImportForm : Form
{
private BackgroundWorker _worker;
public ImportForm()
{
InitializeComponent();
_worker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true,
};
_worker.DoWork += Worker_DoWork;
_worker.ProgressChanged += Worker_ProgressChanged;
_worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}
private void btnStart_Click(object sender, EventArgs e)
{
_worker.RunWorkerAsync();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
//バックグラウンドスレッドで動く(UI触れない)
for (int i = 0; i < 100; i++)
{
if (_worker.CancellationPending){ e.Cancel = true; return; }
Thread.Sleep(50);
_worker.ReportProgress(i + 1);
}
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// UIスレッドで動く(直接コントロール触れる)
progressBar1.Value = e.ProgressPercentage;
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null){ MessageBox.Show($"エラー: {e.Error.Message}"); return; }
if (e.Cancelled){ lblStatus.Text = "キャンセルされました"; return; }
lblStatus.Text = "完了";
}
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「定石1: BackgroundWorker —旧式だがDesigner配置できる」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
5 件// ✅定石2: Task.Run + Control.Invoke using System.Threading.Tasks; public partial class ImportForm : Form未収録
定石2: Task.Run + Control.Invokeでモダンに書く
#e29c62a2a0b1
// ✅定石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
