如何使用VS2010重置CancellationTokenSource并调试多线程?
|
我已经使用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();
}
没有找到相关结果
已邀请:
5 个回复
稳赣苍卯改
。
不是某种工厂。它只是单个令牌的所有者。海事组织,它应该被称为“ 4”。 问题2>如何在VS2010中调试多线程?如果以调试模式运行该应用程序,则可以看到以下异常语句 这与调试无关。您无法从另一个线程访问gui控件。您需要使用
。我猜您只能在调试模式下看到问题,因为在发布模式下禁用了某些检查。但是错误仍然存在。
届甸衬丝蚕
的ui类中声明ѭ7并将其设置为
来实现此目的 现在有了它,您可以执行一个新任务来更新ui:
请注意,我们在启动任务时将任务计划程序传递给任务。 还有第二种方法,使用TaskContinuation API。但是,我们不能再使用Paralell.Foreach,但是将使用常规的foreach和任务。关键是一个任务允许您安排另一个任务,该任务将在第一个任务完成后运行。但是第二项任务不必在同一调度程序上运行,这对我们现在非常有用,因为我们想在后台做一些工作然后更新ui:
我们在这里所做的是在每个循环中创建一个新任务,以完成工作并生成消息,然后我们挂接到了另一个实际上将更新ui的任务。 您可以在此处阅读有关ContinueWith和延续的更多信息
冲汉
奥李
接下来是vb.net:
现在的C#:
享受代码!
香腔弥胯瓤
丑陋有地狱,但行得通。我最终必须找到更好的解决方案。