后台工作者中的 Dowork() 究竟是做什么的?

What is Dowork() in background worker exactly do?

我有一个困惑:在后台工作者的每一个演示中。他们把 Thread.Sleep(); 放在这个方法中来模拟长时间的操作。但是如果我有一个从数据库导入数据到数据表的操作,我调用了这个方法:importData()。我用它替换 Thread.Sleep(); 。也就是说它会被导入100次?谢谢你的回答。

 void worker_DoWork(object sender, DoWorkEventArgs e)
            {
                    for(int i = 0; i < 100; i++)
                    {
                            (sender as BackgroundWorker).ReportProgress(i);
                            Thread.Sleep(100);
                    }
            }

DoWork是一个后台工作者的重头戏。这意味着它必须在后台完成的工作将在该事件中完成。

如果您将 ImportData() 方法放在 for-loop 中,那么是的,您的数据将被导入 100 次,或者您添加的任何变量而不是 100 次。

但是您不需要在 for-loop 中完成工作,只需跳过 for-loop 部分并完成 ImportData() 部分

来自MSDN的评论:

This event is raised when you call the RunWorkerAsync method. This is where you start the operation that performs the potentially time-consuming work.

Your code in the DoWork event handler should periodically check the CancellationPending property value and abort the operation if it is true. When this occurs, you can set the Cancel flag of System.ComponentModel.DoWorkEventArgs to true, and the Cancelled flag of System.ComponentModel.RunWorkerCompletedEventArgs in your RunWorkerCompleted event handler will be set to true.