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#中创建多个线程


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01