简体   繁体   English

仅在主线程执行完成后,后台工作线程中的函数调用才会执行?

[英]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. 我在后台工作线程上调用一个函数,该函数要求将ListBox作为初始化在主线程上的参数传递。 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. 问题在于ShowLoadingPanel函数仅在GetData函数完成执行后才调用。 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. 您的示例没有多大意义:您想将ShowLoadingPanel卸载到另一个(非GUI)线程,但是可以使用Control.Invoke执行它,该文档记录为在拥有控件基础窗口句柄的线程上执行指定的委托。 , ie executes on the GUI thread. ,即在GUI线程上执行。

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. Control.Invoke将消息发布到拥有窗体窗口的线程的消息队列中,您可以通过Click handler(已作为消息处理)进行操作。 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. 因此,只有在您的Click处理程序退出后,才可以处理Control.Invoke张贴到队列中的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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