Skip to main content
 首页 » 编程设计

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

2024年02月13日13mq0036

我是 .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!!! 
    } 
} 

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

请您参考如下方法:

你有几个选择:

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

  2. 使用 TPL Library通过以下方式:

    Task.Run(() =>  
      { 
        //do work 
      }).ContinueWith(() =>  
          { 
              //do continuation 
          }, TaskScheduler.FromCurrentSynchronizationContext); 
    
  3. 在后台线程中使用 Application.Current.BeginInvoke 或 Application.Current.Invoke