進捗状況画面の表示
最近だとこういう風に書くみたいですね。楽ちん。
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; /* * デザイン上に、ProgressBar, Button2つ を張り付けています。 * * */ namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // 開始ボタン private CancellationTokenSource TokenSource = new CancellationTokenSource(); private async void button1_Click(object sender, EventArgs e) { // 専用処理の準備と実行 var items = Enumerable.Range(1, 10); var progress = new Progress<int>(value => { progressBar1.Value = value; }); progressBar1.Minimum = 0; progressBar1.Maximum = items.Count(); progressBar1.Value = 0; // メイン処理お任せ await DoWork(progress, items); // 処理終了後の調整 if (TokenSource.IsCancellationRequested) Text = "Canceled."; else Text = "Completed!"; } private async Task DoWork(IProgress<int> progress, IEnumerable<int> items) { foreach (var item in items) { if (TokenSource.IsCancellationRequested) break; progress.Report(item); await Task.Delay(1000); } } // 中止ボタン private void button2_Click(object sender, EventArgs e) { TokenSource.Cancel(); } } }