如何在c#中创建多个线程

How to create multiple threads in c#(如何在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#中创建多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)