任务同步
我有一个在 tpl 的任务中执行的算法。
在每次迭代中,我想执行一个事件处理程序,该事件处理程序更新 winforms 客户端中的进度条(通过 mvp 预设器)。
public delegate void NotifyAboutIterationEnd(int iteration);
public event NotifyAboutIterationEnd Notify;
var task = Task.Factory.StartNew(() =>
{
foreach (..
{
var t = Task.Factory.StartNew(p =>
{
Notify(++index);
},CancellationToken.None,TaskCreationOptions.None,Scheduler);
foreach (..
问题是,在调试模式下,我首先看到的是执行主任务中的代码。当这段代码结束时,调试器将转到内部任务。我怎样才能同步它?我想在每次迭代中更新进度条。现在的效果是,我已经在 datagridview 中得到了算法结果,然后我看到工作(更新)进度条:/
I have an algorithm which is executted in task from tpl.
From each iteration I want to execute an event handler which update the progress bar in winforms client (throught mvp preseter)
public delegate void NotifyAboutIterationEnd(int iteration);
public event NotifyAboutIterationEnd Notify;
var task = Task.Factory.StartNew(() =>
{
foreach (..
{
var t = Task.Factory.StartNew(p =>
{
Notify(++index);
},CancellationToken.None,TaskCreationOptions.None,Scheduler);
foreach (..
The problem is that, in debug mode I see first is executing the code from the main task. When this code is over, then debugger goes to the inner task. How can I synchronize it? I want to update the progress bar in each iteration. Now the effect is that, I have algorithm result in datagridview already and then I see working (updateing) progress bar :/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您的
Scheduler
变量是 UI 同步上下文的TaskScheduler
实例,因此您只是尝试通过使用任务 API 来保持一致,而不是仅使用 <直接代码>Control/Window::Invoke?同步的唯一方法是调用 t.Wait()。这显然会阻止您的并行工作继续进行,直到对
Notify
的调用完成,但如果您确实需要 UI 与进度同步,那么这是唯一的方法。I assume you're
Scheduler
variable is theTaskScheduler
instance for the UI synchronization context and so you're just trying to be consistent by using the Task API isntead of just usingControl/Window::Invoke
directly?The only way to synchronize would be to call
t.Wait()
. This will obviously block your parallel work from continuing until the call toNotify
completes, but if you really need the UI to be synchronized with the progress then this is the only way.