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

本文标题为:如何在c#中创建多个线程

基础教程推荐