我需要监听机器中的所有串行端口。假设我的机器有 4 个串行端口,我必须创建 4 个线程并开始分别使用附加线程监听每个端口。
我使用此代码来获取我的机器中的端口数量。
private SerialPort comPort = new SerialPort();
public void GetAllPortNamesAvailable()
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
//How to start a thread here ??
}
}
public void AssignThreadtoPort()
{
string msg = comPort.ReadLine();
this.GetMessageRichTextBox("Message : " + msg + "\n");
}
阅读评论后,我正在使用这段代码,但没有收到消息..有什么问题吗?
public void AssignThreadsToPorts()
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
SerialPort sp = new SerialPort();
sp.PortName = port;
sp.Open();
new Thread(() =>
{
if (sp.IsOpen)
{
string str = sp.ReadLine().ToString();
MessageBox.Show(str);
}
}).Start();
}
}
你可以使用线程池 http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
ThreadPool.QueueUserWorkItem(state =>
{
// This will execute in a new thread
});
}
或创建并启动threads http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx手动:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
new Thread(() =>
{
// This will execute in a new thread
}).Start();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)