您好,欢迎光临本网站![请登录][注册会员]  
文件名称: C#多线程串口通信
  所属分类: C#
  开发工具:
  文件大小: 67kb
  下载次数: 0
  上传时间: 2013-12-15
  提 供 者: shangs******
 详细说明: 这是一个非常经典的C#串口多线程实例,把部分代码发送来让大家看看 using System; using System.IO; using System.IO.Ports; using System.Collections; using System.Threading; namespace Termie { /// CommPort class creates a singleton instance /// of SerialPort (System.IO.Ports) /// When ready, you open the port. /// /// CommPort com = CommPort.Instance; /// com.StatusChanged += OnStatusChanged; /// com.DataReceived += OnDataReceived; /// com.Open(); /// < /code> /// Notice that delegates are used to handle status and data events. /// When settings are changed, you close and reopen the port. /// /// CommPort com = CommPort.Instance; /// com.Close(); /// com.PortName = "COM4"; /// com.Open(); /// /// public sealed class CommPort { SerialPort _serialPort; Thread _readThread; volatile bool _keepReading; //begin Singleton pattern static readonly CommPort instance = new CommPort(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static CommPort() { } CommPort() { _serialPort = new SerialPort(); _readThread = null; _keepReading = false; } public static CommPort Instance { get { return instance; } } //end Singleton pattern //begin Observer pattern public delegate void EventHandler(string param); public EventHandler StatusChanged; public EventHandler DataReceived; //end Observer pattern private void StartReading() { if (!_keepReading) { _keepReading = true; _readThread = new Thread(ReadPort); _readThread.Start(); } } private void StopReading() { if (_keepReading) { _keepReading = false; _readThread.Join(); //block until exits _readThread = null; } } /// Get the data and pass it on. private void ReadPort() { while (_keepReading) { if (_serialPort.IsOpen) { byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1]; try { // If there are bytes available on the serial port, // Read returns up to "count" bytes, but will not block (wait) // for the remaining bytes. If there are no bytes available // on the serial port, Read will block until at least one byte // is available on the port, up until the ReadTimeout milliseconds // have elapsed, at which time a TimeoutException will be thrown. int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize); String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer,0,count); DataReceived(SerialIn); } catch (TimeoutException) { } } else { TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50); Thread.Sleep(waitTime); } } } /// Open the serial port with current settings. public void Open() { Close(); try { _serialPort.PortName = Settings.Port.PortName; _serialPort.BaudRate = Settings.Port.BaudRate; _serialPort.Parity = Settings.Port.Parity; _serialPort.DataBits = Settings.Port.DataBits; _serialPort.StopBits = Settings.Port.StopBits; _serialPort.Handshake = Settings.Port.Handshake; // Set the read/write timeouts _serialPort.ReadTimeout = 50; _serialPort.WriteTimeout = 50; _serialPort.Open(); StartReading(); } catch (IOException) { StatusChanged(String.Format("{0} does not exist", Settings.Port.PortName)); } catch (UnauthorizedAccessException) { StatusChanged(String.Format("{0} already in use", Settings.Port.PortName)); } catch (Exception ex) { StatusChanged(String.Format("{0}", ex.ToString())); } // Update the status if (_serialPort.IsOpen) { string p = _serialPort.Parity.ToString().Substring(0, 1); //First char string h = _serialPort.Handshake.ToString(); if (_serialPort.Handshake == Handshake.None) h = "no handshake"; // more descriptive than "None" StatusChanged(String.Format("{0}: {1} bps, {2}{3}{4}, {5}", _serialPort.PortName, _serialPort.BaudRate, _serialPort.DataBits, p, (int)_serialPort.StopBits, h)); } else { StatusChanged(String.Format("{0} already in use", Settings.Port.PortName)); } } /// Close the serial port. public void Close() { StopReading(); _serialPort.Close(); StatusChanged("connection closed"); } /// Get the status of the serial port. public bool IsOpen { get { return _serialPort.IsOpen; } } /// Get a list of the available ports. Already opened ports /// are not returend. public string[] GetAvailablePorts() { return SerialPort.GetPortNames(); } /// Send data to the serial port after appending line ending. /// An string containing the data to send. public void Send(string data) { if (IsOpen) { string lineEnding = ""; switch (Settings.Option.AppendToSend) { case Settings.Option.AppendType.AppendCR: lineEnding = "\r"; break; case Settings.Option.AppendType.AppendLF: lineEnding = "\n"; break; case Settings.Option.AppendType.AppendCRLF: lineEnding = "\r\n"; break; } _serialPort.Write(data + lineEnding); } } } } ...展开收缩
(系统自动生成,下载前可以参看下载内容)

下载文件列表

相关说明

  • 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
  • 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度
  • 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
  • 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
  • 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
  • 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.
 相关搜索: C#多线程串口
 输入关键字,在本站1000多万海量源码库中尽情搜索: