【发布时间】:2011-05-29 15:10:59
【问题描述】:
我已经使用 CancellationTokenSource 来提供一个函数,以便用户可以 取消冗长的动作。但是,在用户申请第一次取消后, 后来的进一步行动不再起作用。我的猜测是 CancellationTokenSource 的状态已设置为 Cancel,我想知道如何重置 它回来了。
问题一:第一次使用后如何重置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。
-
我在blogs.msdn.com/b/pfxteam/archive/2009/05/22/9635790.aspx 找到了一篇文章,表明我们无法重置它。解决方案是每次创建一个新的 CancellationTokenSource。这回答了我的第一个问题。但是,我的第二个问题仍然需要帮助。 --- 谢谢
-
第一个问题已回答/解决,第二个问题重复了 100 次。
-
@Henk,我只是不想在这里两次发布我的源代码。 -thx
-
不是一个很好的理由,尤其是因为你不需要大部分代码。
标签: c# .net winforms debugging cancellationtokensource