Csharp/C#教程:如何在c#中创建多个线程分享


如何在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(); } } 

你可以使用线程池 :

 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { ThreadPool.QueueUserWorkItem(state => { // This will execute in a new thread }); } 

或手动创建和启动线程 :

上述就是C#学习教程:如何在c#中创建多个线程分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { new Thread(() => { // This will execute in a new thread }).Start(); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/936364.html

(0)
上一篇 2021年11月7日
下一篇 2021年11月7日

精彩推荐