我是 .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()
方法?
最佳答案
你有几个选择:
正如@ScottChamberlain 在评论中所说,使用
BackgroundWorker
并使用其Completed
事件更新 GUI使用 TPL Library通过以下方式:
Task.Run(() => { //do work }).ContinueWith(() => { //do continuation }, TaskScheduler.FromCurrentSynchronizationContext);
在后台线程中使用
Application.Current.BeginInvoke
或Application.Current.Invoke
关于c# - 子线程结束后如何在主线程中运行一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035480/