Background worker proper way to access UI

自作多情 提交于 2019-11-30 09:45:04

You can pass data into the worker via the argument of the RunWorkerAsync call and pass data out via DoWorkEventArgs.Result...

  class AuthUserData
  {
    public string Name;
    public string Password;
  }

  private void button1_Click(object sender, EventArgs e)
  {
     var authData = new AuthUserData() { Name = textBox1.Text, Password = textBox2.Text };
     worker.RunWorkerAsync(authData);
  }

  void worker_DoWork(object sender, DoWorkEventArgs e)
  {
     // On the worker thread...cannot make UI calls from here.
     var authData = (AuthUserData)e.Argument;
     UserManagement um = new UserManagement(sm.GetServerConnectionString());
     e.Result = um;
     e.Cancel = um.AuthUser(textBox1.Text, textBox2.Password));
  }

  void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  {
     // Back on the UI thread....UI calls are cool again.
     var result = (UserManagement)e.Result;
     if (e.Cancelled)
     {
        // Do stuff if UserManagement.AuthUser succeeded.
     }
     else
     {
        // Do stuff if UserManagement.AuthUser failed.
     }
  }

As the name implies, the Background Worker does not run on the UI thread. You can only access UI controls when on the UI thread. An easy way to work around this issue, is to save the text box properties you need in a need a new "object" and then pass it to RunWorkerAsync. This object is available to your DoWork method in e.Argument.

However, you also have an issue with showing a form on a worker thread.

You cannot access UI elements directly from a BackgroundWorker.To do so you have to use Dispatcher. WPF objects which derive from DependencyObject have thread affinity which means that only the thread that instantiates them can access their members.

Check the link below and see if the code sample helps you

http://social.msdn.microsoft.com/Forums/en/wpf/thread/4858bcaf-1cb2-410b-989a-18b874ffa458

this.Dispather.Invoke((Action)delegate(){
    this.Close();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!