我已經使用CancellationTokenSource提供了一個函數,以便用戶可以取消這個冗長的動作 。但是,在用戶應用第一次取消後,後面的進一步操作不再起作用。我的猜測是CancellationTokenSource的狀態已設置爲取消,我想知道如何重置 。如何重置CancellationTokenSource並使用VS2010調試多線程?
問題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();
}
如果您取消它,則會取消並且無法恢復。你需要一個新的CancellationTokenSource。 – CodesInChaos 2011-05-29 15:12:21
我在這裏發現了一篇文章http://blogs.msdn.com/b/pfxteam/archive/2009/05/22/9635790.aspx,指出我們無法重置它。解決方案是每次創建一個新的CancellationTokenSource。這回答了我的第一個問題。但是,對於第二個問題,我仍然需要幫助。 --- thx – q0987 2011-05-29 15:16:23
對每個問題嘗試1個問題 – 2011-05-29 15:41:26