BackgroundWorker ReportProgress 无循环,仅进行长数据库操作

Izt*_*son 5 c# vb.net winforms

我有 .NET 4.5 Windows 窗体应用程序,其中一种方法需要一段时间才能完成(它是一个 BulkCopy 函数,会加载大量数据并推送到 SQL 中)。

I would like to use a BackgroundWorker and ReportProgress so the user will know that there is something going on. I made a few applications that use this but all of them are in some kind of a loop when the BackgroundWorker is doing work and I can easily ReportProgress inside each loop step.

Here I have a problem because there is no loop, code steps would be:

  1. worker start async
  2. get data from DB2 into a datatable (this takes the most time)
  3. SqlBulkCopy datatable into SQL table

I would need to start reporting progress (albeit a fake progress percentage, a simple spinning progress bar would suffice) between step 1. and 2. and end reporting progress after step 3.

Anyone had a similar problem/solution, I guess I could just display a GIF image and hide it after work is done, but I think this won't work as the form freezes (Not responding message).

Lar*_*ech 4

您可以使用 ProgressBar 的 Marquee 样式来显示活动进程的不确定长度:

BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 50;
bgw.RunWorkerAsync();

void bgw_DoWork(object sender, DoWorkEventArgs e) {
  // long work
}

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
  progressBar1.Style = ProgressBarStyle.Continuous;
  progressBar1.MarqueeAnimationSpeed = 0;
}
Run Code Online (Sandbox Code Playgroud)