DoWork of BackgroundWorker is called twice when RunWorkerAsync is called once?

前端 未结 7 1307
情深已故
情深已故 2020-12-06 01:51

I have create a backgroundworker in an class it works, but if i call and wait until the end run, call it for the second time it will do the same process twice

i thin

7条回答
  •  情歌与酒
    2020-12-06 01:54

    thank you....this code is working fine... creating new intance for backroundworker is good idea.... Now we can call this function in for/while loop and can run multiple backgroundworker process.

    I coded like this when button click is done.. without distrubting the main thread flow... multiple process will be running back side.... i just used messagebox to pop up..but we can do timetaking process to run in "bgwDownload_DoWork" function... and multiple process will be created... and her we need not check the BackgroundWorker is busy or not...

    private void button1_Click(object sender, EventArgs e)
    {
       for (int i = 0; i < 3; i++)
         yourFunction_bw(i);
    
     }
    private BackgroundWorker gBgwDownload;
    
    private void yourFunction_bw(int i)
    {
        // Create a background thread
        gBgwDownload = new BackgroundWorker(); // added this line will fix problem 
        gBgwDownload.DoWork += bgwDownload_DoWork;
        gBgwDownload.RunWorkerAsync(i);
    
    }
    
    private void bgwDownload_DoWork(object sender, DoWorkEventArgs e)
    {
      int stre = (int)e.Argument;
      MessageBox.Show(stre.ToString ()); // time taken process can be added here
    }
    

提交回复
热议问题