BackgroundWorker ReportProgress no loop only a long database operation

I have a .NET 4.5 Windows Forms application where one of the methods takes time to complete (this is the BulkCopy function, which loads a significant amount of data and inserts into SQL).

I would like to use BackgroundWorker and ReportProgress so that the user knows that something is happening. I have made several applications that use this, but they are all in some kind of loop when BackgroundWorker is doing the work, and I can easily ReportProgress inside each step of the loop.

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

  • working start of async
  • get data from DB2 into datatable (this takes longer)
  • SqlBulkCopy datatable to SQL table

I would need to start reporting progress (although a fake percentage of progress, a fairly simple progress indicator) between steps 1. and 2. and complete reporting after step 3.

Someone had a similar problem / solution, I think I could just display the GIF image and hide it after the work is completed, but I think this will not work as the form freezes (message does not respond).

+4
source share
4 answers

You can use the Marquee style for the ProgressBar to show the indefinite length of the active process:

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;
}
+3
source

GIF . , . , , , . , .

+2

Timer/Thread .

 try  {
        // Start a Timer                     
       // Write from the source to the destination.
                bulkCopy.WriteToServer(reader);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Close the SqlDataReader. The SqlBulkCopy 
                // object is automatically closed at the end 
                // of the using block.
                reader.Close();
               // Stop the Timer
            }
+1

, :

    private DataTable dt = new DataTable();

    void Start()
    {
        dt.RowChanged += new DataRowChangeEventHandler(dt_RowChanged);
        progressBar1.Maximum = dtRowsCount;
        bgWorker.RunWorkerAsync();
    }

    void dt_RowChanged(object sender, DataRowChangeEventArgs e)
    {
        bgWorker.ReportProgress(1);
    }

    void bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Your work
    }

    void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value += e.ProgressPercentage;
    }
+1

Source: https://habr.com/ru/post/1536779/


All Articles