Catalog
Chapter 1 explains 2
1 Why do I need to write data asynchronously? 2
2 code to write data asynchronously 2
3 Source Code 4
Section 1 Chapters Description
1 Why do I need to write data asynchronously?
as shown in the baud rate - Open a serial port.
Figure 1
When you click the Send synchronously button, the function that writes the data before the data is sent does not return. Baud rate of about three characters per second can be sent, It takes three seconds to Send the characters . Within these seconds, The entire program will be in suspended Animation.
If you click the "send asynchronously" button, the suspended animation will not appear.
2 code to write data asynchronously
The code for writing data asynchronously is as Follows:
private void Btnwriteasync_click (object sender, EventArgs e) {// Asynchronous Write byte[] byt = System.Text.Encoding.Default.GetBytes (txtsend.text); If (byt!=null && byt. Length > 0) { IntPtr Hcomm = Getcommhandle (m_sp); UInt32 W = 0; M_ov.hevent = intptr.zero; M_ov. Internal = intptr.zero; M_ov. Internalhigh = intptr.zero; M_ov. Offset = 0; M_ov. Offsethigh = 0; WriteFile (hcomm, byt, (UInt32) byt. Length, ref w, ref m_ov); } } |
Key points Are:
1 ) Getcommhandle function gets . NET SerialPort the serial handle of the object Hcomm ;
2 ) Call WriteFile function to write data asynchronously.
here is the structure OVERLAPPED the declaration, function WriteFile the declaration, function Getcommhandle implementation Of:
[structlayout (layoutkind.sequential,pack=4)] public struct OVERLAPPED { Public IntPtr Internal; Public IntPtr internalhigh; Public UInt32 Offset; Public UInt32 offsethigh; Public IntPtr hevent; } [DllImport ("kernel32.dll", SetLastError = True , callingconvention = callingconvention.winapi)] private static extern UInt32 WriteFile (IntPtr hfile, byte[] lpbuffer , UInt32 Nnumberofbytestowrite , ref UInt32 Lpnumberofbyteswritten , ref OVERLAPPED lpoverlapped); protected System.IO.Ports.SerialPort m_sp = New System.IO.Ports.SerialPort (); Protected OVERLAPPED m_ov; Static INTPTR Getcommhandle (System.IO.Ports.SerialPort Sp) {// get the serial port handle for use by the Win32 API IntPtr Hcomm = intptr.zero; If (sp! = Null) { Object stream = typeof (System.IO.Ports.SerialPort). GetField ("internalserialstream", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance). GetValue (sp); var handle = (Microsoft.Win32.SafeHandles.SafeFileHandle) Stream. GetType (). GetField ("_handle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance). GetValue (stream); Hcomm = Handle. DangerousGetHandle (); } Return hcomm; } |
3 Source Code
the code for this article has been uploaded to git server:
Https://github.com/hanford77/Exercise
Https://git.oschina.net/hanford/Exercise
in the catalog serialport\c# within the Directory.
Serial communication Of. NET serialport Asynchronous Write data