如何在子线程结束后在主线程中运行一个方法?

时间:2014-04-12 20:02:31

标签: c# .net multithreading task-parallel-library async-await

我是.Net Threads的新手。我知道我们不能在主线程中使用WinForm GUI。 我想要一个更新WinForm GUI的方法,在第二个线程结束后立即在主线程中运行。 这是我的代码的一部分:

public class FormGApp : Form
{
    private Thread m_LoginThread;

    private void buttonLogin_Click(object sender, EventArgs e)
    {
        m_LoginThread = new Thread(new ThreadStart(this.login));                   
        m_LoginThread.Start();                 
    }

    private void login()
    {
        LoginResult result = loginToServer();
        this.User = result.LoggedInUser;
    }

    private void successfullyLogin()
    {
        // Update the WinForn GUI here...
        // This method must run in the main thread!!!
    }
}

如何在successfullyLogin()结束时运行方法m_LoginThread

3 个答案:

答案 0 :(得分:3)

您有几个选择:

  1. 正如@ScottChamberlain在评论中所说,使用BackgroundWorker并使用其Completed事件来更新GUI

  2. 以下列方式使用TPL Library

    Task.Run(() => 
      {
        //do work
      }).ContinueWith(() => 
          {
              //do continuation
          }, TaskScheduler.FromCurrentSynchronizationContext);
    
  3. 使用后台主题中的Application.Current.BeginInvokeApplication.Current.Invoke

答案 1 :(得分:1)

如果您使用的是.Net 4.5,则可以使用async / await

async private void buttonLogin_Click(object sender, EventArgs e)
{
    await Task.Run(() => login());
    successfullyLogin();
}

答案 2 :(得分:0)

感谢大家鼓励我使用BackgroundWorker,它确实解决了这个问题。 这是我的解决方案:

public partial class FormGApp : Form
{
    private BackgroundWorker m_LoginBackgroundWorker;

    // ctor:
    public FormGApp()
    {
         // init thread:
         this.m_LoginBackgroundWorker = new BackgroundWorker();
         this.m_LoginBackgroundWorker.DoWork += this.LoginBackgroundWorker_DoWork;
         this.m_LoginBackgroundWorker.RunWorkerCompleted += this.LoginBackgroundWorker_RunWorkerCompleted;
    }

    private void buttonLogin_Click(object sender, EventArgs e)
    {
         // start thread:
         this.m_LoginBackgroundWorker.RunWorkerAsync();
    }

    private void LoginBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
         this.login();
    }

    private void LoginBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
         this.successfullyLogin();
    }

    private void login()
    {
         // code that take long time that executed in a separate thread... 
    }

    private void successfullyLogin()
    {
         // Gui WinForm update code here...
    }