【发布时间】:2015-06-14 00:02:18
【问题描述】:
我的 Winforms C# 应用程序遇到了一些问题。
我希望在主线程中的一些操作完成后关闭名为Popup 的表单。问题是跨线程表单关闭导致的异常。
private void loginButton_Click(object sender, EventArgs e)
{
LoginProcess.Start(); // Running Form.show() in new thread
ActiveAcc.IsValid = false;
ActiveAcc.Username = userBox.Text;
try
{
LoginCheck(userBox.Text, passBox.Text);
}
catch (IOException)
{
MessageBox.Show("..");
return;
}
catch (SocketException)
{
MessageBox.Show("..");
return;
}
if (ActiveAcc.IsValid)
{
MessageBox.Show("..");
Close();
}
else
{
Popup.Close(); // Error caused by closing form from different thread
MessageBox.Show("");
}
}
public Login() // 'Main' form constructor
{
InitializeComponent();
ActiveAcc = new Account();
Popup = new LoginWaiter();
LoginProcess = new Thread(Popup.Show); //Popup is an ordinary Form
}
我一直在尝试使用各种工具,例如LoginProcess.Abort() 或Popup.Dispose() 使其正常工作,但即使应用程序在运行时环境中工作,由于抛出异常,它仍然不稳定。
如有任何帮助,我将不胜感激,对于问题描述中的含糊之处,我深表歉意。
【问题讨论】:
-
维护具有多个 UI 线程的应用程序是一种残酷的惩罚,我不希望我最大的敌人受到惩罚。帮自己一个忙,只需将您的应用程序限制为恰好 1 个 UI 线程。让 UI 线程完成所有 UI 工作,并在非 UI 线程中完成任何长时间运行的非 UI 工作。
标签: c# multithreading winforms