如何在c#中创建多线程
我需要监听机器中的所有串行端口。假设我的机器有 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();
}
}
I am need to listen to all the serial ports in my machine. Say if my machine has 4 serial ports, i have to create 4 threads and start listening to each port with the attached thread respectively.
I used this code to get the number of ports in my machine..
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");
}
After reading the comments i am using this code but not getting messages.. what is the problem ?
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用线程池:
或创建并手动启动线程:
You could use the thread pool:
or create and start the threads manually: