Posted at

Taskで非同期処理


何を使えば良いか

Task.Runを使えば良さそう。

Task.Start ×Task.Run × TaskFactory.StartNew

https://www.kinakomotitti.net/entry/2018/06/13/201431


Task.Run

```csharp: MainForm.cs

private void button1_Click(object sender, EventArgs e)

{

Action action = (int i) =>

{

Thread.Sleep(100);

System.Diagnostics.Debug.WriteLine(i);

};

var form = new ProgressDialog();

form.DoWorkAsync(action);
form.ShowDialog();

}

```

```csharp: ProgressDialog.cs

public partial class ProgressDialog : Form

{

private CancellationTokenSource _cts;

public ProgressDialog()

{
InitializeComponent();
this.ControlBox = false;
}

private void ShowProgress(int percent)
{
progressBar1.Value = percent;
label1.Text = percent + " %";
}

public async void DoWorkAsync(Action<int> action)
{
IProgress<int> progress = new Progress<int>(ShowProgress);

_cts = new CancellationTokenSource();
var token = _cts.Token;

try
{
// ★await後、UIスレッドに戻る
await Task.Run(() =>
{
for (int i = 1; i <= 100; i++)
{
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
action(i);
progress.Report(i);
}
});
}
catch (OperationCanceledException)
{
label1.Text = "canceled!!!";
}
finally
{
this.ControlBox = true;
}
}

private void button1_Click(object sender, EventArgs e)
{
_cts.Cancel();
}

}

```