我希望在用户关闭表单之前将Windows窗体应用程序与服务器断开连接。因此,我使用FormClosing事件;
FormClosing += FormManager_FormClosing;
我尝试使用Backgroundworker或没有Backgroundworker,但它无法正常工作。
我编写的代码;
public partial class MqttManager : Form
{
MqttHandler mqttHandler = new MqttHandler();
...
public MqttManager()
{
InitializeComponent();
...
// Specify what will happen while form is closing.
FormClosing += MqttManager_FormClosing;
}
/// <summary>
/// Disconnect from the broker while form is closing.
/// </summary>
private void MqttManager_FormClosing(object sender, FormClosingEventArgs e)
{
bool isDisconnected = mqttHandler.Disconnect();
while (!isDisconnected)
{
System.Threading.Thread.Sleep(1000);
}
//disconnBgWorker.RunWorkerAsync();
}
private void disconnBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
statusPctBox.WaitOnLoad = false;
statusPctBox.Image = Properties.Resources.bigCircle;
System.Threading.Thread.Sleep(1000);
}
private void disconnBgWorker_RunWorkerCompleted(
object sender,
RunWorkerCompletedEventArgs e)
{
bool isDisconnected = mqttHandler.Disconnect();
if (isDisconnected)
{
statusPctBox.Image = Properties.Resources.x32;
flag = true;
}
else
statusPctBox.Image = Properties.Resources.ok32;
}
}
class MqttHandler
{
...
public MqttHandler() { }
...
/// <summary>
/// Disconnect from the broker.
/// </summary>
public bool Disconnect()
{
try
{
client.Disconnect();
return true;
}
catch (Exception)
{
return false;
}
}
}
编辑:“使用while(!isDisconnected)”时,我得到“System.Windows.Forms.dll中发生了'System.ObjectDisposedException'类型的未处理异常 附加信息:无法访问已处置的对象。“表单关闭后的消息。
解决方案:首先,谢谢你们所有人。我在代码上发现了自己的错误。断开连接后,触发了一个事件处理程序并尝试使用“Invoke”更改UI元素。那一刻发生了错误。为了解决这个问题,我断开连接后从相关对象中删除了相关的事件处理程序。