如何使BackgroundWorker ProgressChanged事件按顺序执行? [英] How to make BackgroundWorker ProgressChanged events execute in sequence?

查看:93
本文介绍了如何使BackgroundWorker ProgressChanged事件按顺序执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

private static BackgroundWorker bg = new BackgroundWorker();

static void Main(string[] args) {
  bg.DoWork += bg_DoWork;
  bg.ProgressChanged += bg_ProgressChanged;
  bg.WorkerReportsProgress = true;
  bg.RunWorkerAsync();

  Thread.Sleep(10000);
}

static void bg_ProgressChanged(object sender, ProgressChangedEventArgs e) {
  Console.WriteLine(e.ProgressPercentage);
  Thread.Sleep(100);
  Console.WriteLine(e.ProgressPercentage);
}

static void bg_DoWork(object sender, DoWorkEventArgs e) {
  for (int i = 0; i < 10; i++) {
    bg.ReportProgress(i);
  }
}

运行时,我得到以下输出:

When run I get the following output:

01个1个2个032个3544657786989

0 1 1 2 0 3 2 3 5 4 4 6 5 7 7 8 6 9 8 9

我了解到问题是BackgroundWorker在每次调用ReportProgress时启动的线程之间的竞争状态.

I understand that the issue is a race condition between the threads that BackgroundWorker starts for each call to ReportProgress.

如何确保每个bg_ProgressChanged的整个主体按照我调用它们的顺序执行?那就是我想得到

How can I make sure that the whole body of each bg_ProgressChanged gets executed in the order I have called them? That is I would like to get

0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9

0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9

因此.

推荐答案

BackgroundWorker 在名为 RunWorkerAsync()的线程的当前SynchronizationContext上引发 ProgressChanged 事件..

BackgroundWorker raises ProgressChanged events on the current SynchronizationContext of the thread that called RunWorkerAsync().

默认的SynchronizationContext在ThreadPool上运行回调,而没有任何同步.

The default SynchronizationContext runs callbacks on the ThreadPool without any synchronization.

如果在UI应用程序(WPF或WinForms)中使用BackgroundWorker,它将使用该UI平台的SynchronizationContext,后者将按顺序执行回调.

If you use BackgroundWorker in a UI application (WPF or WinForms), it will use that UI platform's SynchronizationContext, which will execute callbacks in order.

这篇关于如何使BackgroundWorker ProgressChanged事件按顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆