原贴地址:http://blog.sina.com.cn/s/blog_7223c1af0100nryn.html
@H_301_3@PS:不用异步,有时问题很是莫名其妙,郁闷了很久才想到是这个的原因
本文在VB.NET中利用异步委托调用的方法,将串口的自收自发放进一个单独线程,具体实现如下: (1)声明代理(委托) Private Delegate Sub dele_1() (2)定义自收自发函数 Private Sub Communicate() SerialPort1.Open() SerialPort1.WriteLine(txtSend.Text.Trim()) System.Threading.Thread.Sleep(100) txtShow.Text = SerialPort1.ReadExisting() SerialPort1.Close() End Sub (3)定义异步回调函数 Private Sub result(ByVal ar As IAsyncResult) '获得委托对象的引用 Dim deleg As dele_1 = DirectCast(ar.AsyncState,dele_1) deleg.EndInvoke(ar) End Sub (4)点击按钮Button时,开始异步掉用;在BeginInvoke的第一个参数中获得异步回调函数的地址,线程结束后自动执行异步回调函数 Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click Dim dele As New dele_1(AddressOf Communicate) '开始异步调用 Dim ar As IAsyncResult ar = dele.BeginInvoke(New AsyncCallback(AddressOf result),dele) End Sub (5)窗体Load事件 '下面这句话很重要,使得异步出来的线程可以访问主线程创建的控件 Control.CheckForIllegalCrossThreadCalls = False '串口初始化 SerialPort1.PortName = "COM1" SerialPort1.BaudRate = 9600 SerialPort1.StopBits = IO.Ports.StopBits.One SerialPort1.Parity = IO.Ports.Parity.None SerialPort1.ReadTimeout = 3000 SerialPort1.DataBits = 8 txtSend.Text = "11111111" (6)调试运行 实现了串口的自收自发。 本文还有很多不足之处,请大家多多指点。原文链接:https://www.f2er.com/vb/259190.html