简体   繁体   中英

function call in background worker thread get executed only after main thread execution complete?

I am calling a function on background worker thread which requires ListBox to be passed as parameter which intialize on main thread. I am using following code to do

   private void simpleButton1_Click(object sender, EventArgs e)
    {            
        bw.RunWorkerAsync();           
        GetData()         

    }
void bw_DoWork(object sender,DoWorkEventArgs e)
    {           
        this.Invoke(new MethodInvoker(delegate
        {
            ShowLoadingPanel(listBox);
        }));            
    }

private void GetData()
      {
        for (int i = 0; i < 500000; i++)
        {
            datatable.Rows.Add(new object[] { "raj", "raj", "raj", i });
        }
    }

  void ShowLoadingPanel(Control control)
   {
      //Doing some work here
   }

Problem is that ShowLoadingPanel function called only after GetData function completes its execution. I want this two function run parallel in different threads.

How can i do this ??

Try this:

private void simpleButton1_Click(object sender, EventArgs e)
{        
    ShowLoadingPanel(listBox);    
    bw.RunWorkerAsync();       
}

void bw_DoWork(object sender,DoWorkEventArgs e)
{           
    GetData();
}

private void GetData()
{
    for (int i = 0; i < 500000; i++)
    {
        datatable.Rows.Add(new object[] { "raj", "raj", "raj", i });
    }
}

void ShowLoadingPanel(Control control)
{
   //Doing some work here
}

Your example doesn't make much sense: you want to offload ShowLoadingPanel to another (non-GUI) thread, but you execute it with Control.Invoke which is documented as Executes the specified delegate on the thread that owns the control's underlying window handle. , ie executes on the GUI thread.

Control.Invoke posts a message to the message queue of the thread owning the form window and you do it from button Click handler which is already handled as a message. Thus, the message posted to the queue by Control.Invoke can only be processed after your Click handler exits, which is exactly what you observe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM