How to make BackgroundWorker ProgressChanged events execute in sequence?

后端 未结 2 1193
情歌与酒
情歌与酒 2021-01-11 19:13

Consider the following code:

private static BackgroundWorker bg = new BackgroundWorker();

static void Main(string[] args) {
  bg.DoWork += bg_DoWork;
  bg.P         


        
相关标签:
2条回答
  • 2021-01-11 19:43

    Do not use this solution!!! May lead to deadlocks as SLaks has pointed it out.

    I seem to have stumbled upon an answer. I changed the code the following way:

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

    and now I get the output I want:

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

    0 讨论(0)
  • 2021-01-11 19:54

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

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

    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.

    0 讨论(0)
提交回复
热议问题