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

标签 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!!!
    }
}

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

最佳答案

你有几个选择:

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

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

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

关于c# - 子线程结束后如何在主线程中运行一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035480/

相关文章:

c# - 将 List<Base> 与 List<Derived> 组合

c++ - 调用 shmat 两次

c# - 我可以使用 JavascriptSerializer 反序列化为不可变对象(immutable对象)吗?

c# - NGit rebase 创建新提交

c# - 如何在使用 DapperExtensions 映射时指定 Schema?

python - 停止 Winsound/停止 Python 上的线程

Java:通过多线程并行化快速排序

.net - WCF REST 结果 XML

c# - 用于解析重复组的正则表达式

.net - Windows 服务中的 "net use"命令