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

本文关键字:线程 方法 运行 结束 | 更新日期: 2023-09-27 17:58:07

我是.Net线程的新手。我知道我们不能在主线程之外使用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!!!
    }
}

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

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

您有几个选项:

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

  2. 以以下方式使用TPL库:

    Task.Run(() => 
      {
        //do work
      }).ContinueWith(() => 
          {
              //do continuation
          }, TaskScheduler.FromCurrentSynchronizationContext);
    
  3. 使用背景线程中的Application.Current.BeginInvokeApplication.Current.Invoke

如果您使用.Net 4.5,您可以使用异步/等待

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

感谢大家激励我使用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...
    }