How to create multiple threads in c#(如何在c#中创建多个线程)
问题描述
我需要监听我机器上的所有串口.假设我的机器有 4 个串口,我必须创建 4 个线程并开始分别用附加的线程监听每个端口.
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 + "
");
}
阅读评论后,我正在使用此代码但没有收到消息.. 有什么问题?
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();
}
}
推荐答案
你可以使用 线程池:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
ThreadPool.QueueUserWorkItem(state =>
{
// This will execute in a new thread
});
}
或手动创建并启动 线程:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
new Thread(() =>
{
// This will execute in a new thread
}).Start();
}
这篇关于如何在c#中创建多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在c#中创建多个线程
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30