这是一个非常经典的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();
///
/// 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;
}
}
1