CancellationTokenSource を使用して関数を提供し、ユーザーが長いアクションをキャンセルできるようにしました。ただし、ユーザーが最初のキャンセルを適用すると、その後のアクションは機能しなくなります。私の推測では、CancellationTokenSource のステータスが Cancel に設定されており、それを元に戻す方法を知りたいのです。
質問 1: 初めて使用した後に CancellationTokenSource をリセットする方法を教えてください。
質問 2: VS2010 でマルチスレッドをデバッグする方法は? アプリケーションをデバッグ モードで実行すると、次のステートメントの例外が表示されます。
this.Text = string.Format("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId);
InvalidOperaationException はユーザー コードによって処理されませんでした クロススレッド操作が無効です: コントロール 'MainForm' は、それが作成されたスレッド以外のスレッドからアクセスされました。
ありがとうございました。
private CancellationTokenSource cancelToken = new CancellationTokenSource();
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew( () =>
{
ProcessFilesThree();
});
}
private void ProcessFilesThree()
{
ParallelOptions parOpts = new ParallelOptions();
parOpts.CancellationToken = cancelToken.Token;
parOpts.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
string[] files = Directory.GetFiles(@"C:\temp\In", "*.jpg", SearchOption.AllDirectories);
string newDir = @"C:\temp\Out\";
Directory.CreateDirectory(newDir);
try
{
Parallel.ForEach(files, parOpts, (currentFile) =>
{
parOpts.CancellationToken.ThrowIfCancellationRequested();
string filename = Path.GetFileName(currentFile);
using (Bitmap bitmap = new Bitmap(currentFile))
{
bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
bitmap.Save(Path.Combine(newDir, filename));
this.Text = tring.Format("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId);
}
});
this.Text = "All done!";
}
catch (OperationCanceledException ex)
{
this.Text = ex.Message;
}
}
private void button2_Click(object sender, EventArgs e)
{
cancelToken.Cancel();
}