当我关闭串口Comport时,我的c#表单挂起了。有时它无能为力。 [英] When I close serial Comport, my c# form is hang. Sometimes it can do nothing.

查看:78
本文介绍了当我关闭串口Comport时,我的c#表单挂起了。有时它无能为力。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的先生,您好!

请帮助我。我正在编写一个程序来从串口捕获数据。我可以打开,我可以从该端口捕获数据。但我关闭串口,有时我的端口可以关闭,我的表格挂起,什么也不做。当我在那里遇到Break Point并发送F10时,它不会继续下一行。



public void StopPort()

{

试试

{

myport.Close(); //无法前往下一行。

this.Close();

}

catch(Exception ex)

{

this.Close ();

}

}

谢谢

Thiha Swe

缅甸

解决方案

这似乎是一个已知的comport错误,如下所述:



Social msdn





他们建议在另一个帖子中关闭它,如下所示:



  private   void  Form1_FormClosing( object  sender,FormClosingEventArgs e)

{

if (serialPort1.IsOpen)

{

e.Cancel = true ; // 取消fom结束

线程CloseDown = new 线程( new ThreadStart(CloseSerialOnExit)); // 在新线程中关闭端口以避免挂起

CloseDown.Start( ); // 在新主题中关闭端口以避免挂起

}

}

private void CloseSerialOnExit()

{

尝试

{

serialPort1.Close( ); // 关闭串口

}

catch (Exception ex)

{

MessageBox.Show(ex.Message); // 捕获任何串口关闭错误消息

}

this .Invoke( new EventHandler(NowClose)); // 现在在主线程中关闭

}

private void NowClose( object sender,EventArgs e)

{

this .Close(); // 现在关闭表格

}


我遇到了同样的问题。在我的情况下,在关闭端口之前删除处理程序是解决方案:



 serialPort.ErrorReceived- = ErrorReceived; 
serialPort.DataReceived - = SerialDataReceived;
serialPort.Close();





Bruno


Hello Dear Sir,
Please help me. I am writing a program to catch data from serial port . I can open and I can catch data from that port . But I close the serial port , sometimes my port can be closed and my form is hang , can do nothing. When I catch with Break Point there, and send F10, but it does not go on next line.

public void StopPort()
{
try
{
myport.Close();// cannot go to next line hang around here.
this.Close();
}
catch (Exception ex)
{
this.Close();
}
}
Thanks
Thiha Swe
Myanmar

解决方案

It's seems that's a known bug of comport,as stated here:

Social msdn


They advise to close it in another thread,something like this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)

{

if (serialPort1.IsOpen)

{

e.Cancel = true; //cancel the fom closing

Thread CloseDown = new Thread(new ThreadStart(CloseSerialOnExit)); //close port in new thread to avoid hang

CloseDown.Start(); //close port in new thread to avoid hang

}

}

private void CloseSerialOnExit()

{

try

{

serialPort1.Close(); //close the serial port

}

catch (Exception ex)

{

MessageBox.Show(ex.Message); //catch any serial port closing error messages

}

this.Invoke(new EventHandler(NowClose)); //now close back in the main thread

}

private void NowClose(object sender, EventArgs e)

{

this.Close(); //now close the form

}


I faced the same Problems. In my case removing handlers before closing the port was the solution:

serialPort.ErrorReceived-= ErrorReceived;
serialPort.DataReceived -= SerialDataReceived;
serialPort.Close();



Bruno


这篇关于当我关闭串口Comport时,我的c#表单挂起了。有时它无能为力。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆