How to make BackgroundWorker ProgressChanged events execute in sequence?

后端 未结 2 1194
情歌与酒
情歌与酒 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

提交回复
热议问题