How does BackgroundWorker use async thread to munipulate UI

this is my demo code in vs beta1

private void button1_Click(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork+=new DoWorkEventHandler(worker_DoWork);
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
this.Text = "help me";
}
but when i press the button1,an exception appear
how can i oprete UI in a non-main thread
Help me .thanks a lot.


Answer this question

How does BackgroundWorker use async thread to munipulate UI

  • meo1985

    BackgroundWorker.DoWork event if for the method that's supposed to run asyncronoulsly i.e. not on UI thread, and after it finished it'll invoke RunWorkerCompleted


    private void button1_Click(object sender, EventArgs e) 

    BackgroundWorker worker = new BackgroundWorker(); 
    worker.DoWork+=new DoWorkEventHandler(worker_DoWork); 
    worker.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); 


    // this is not UI
    void worker_DoWork(object sender, DoWorkEventArgs e) 

        // this line should no call UI object
        //  this.Text = "help me"; 
       DoLongWork();
    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 

       // this can run on UI
        this.Text = "help me"; 
    }


  • How does BackgroundWorker use async thread to munipulate UI