如何在C#中多线程 [英] How to create multiple threads in c#
本文介绍了如何在C#中多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要听在我的机器所有的串行端口。说,如果我的机器有4个串口,我要创建4个线程,并开始听取分别与连接线的每个端口。
我用这个代码来获取数在我的机器。
私人的SerialPort COMPORT =新的SerialPort端口();
公共无效GetAllPortNamesAvailable()
{
的String [] =端口SerialPort.GetPortNames();
的foreach(港口串口)
{
//如何在这里启动一个线程?
}
}
公共无效AssignThreadtoPort()
{
弦乐味精= comPort.ReadLine();
this.GetMessageRichTextBox(消息:+味精+\\\
);
}
阅读注释我使用这个代码,但没有得到消息后..什么是什么问题?
公共无效AssignThreadsToPorts()
{
的String [] =端口SerialPort.GetPortNames ();
的foreach(港口串口)
{
的SerialPort SP =新的SerialPort();
sp.PortName =口;
sp.Open();
新的Thread(()=>
{
如果(sp.IsOpen)
{
字符串str = sp.ReadLine()的ToString。 ();
MessageBox.Show(STR);
}
})启动();
}
}
解决方案
您可以使用线程池:
的String [] =端口SerialPort.GetPortNames();
的foreach(港口串口)
{
ThreadPool.QueueUserWorkItem(州=>
{
//这将在一个新的线程
执行});
}
或创建和启动的螺纹手动:
的String [] =端口SerialPort.GetPortNames();
的foreach(港口串口)
{
新的Thread(()=>
{
//这将在一个新的线程
执行})。开始();
}
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 + "\n");
}
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();
}
}
解决方案
You could use the thread pool:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
ThreadPool.QueueUserWorkItem(state =>
{
// This will execute in a new thread
});
}
or create and start the threads manually:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
new Thread(() =>
{
// This will execute in a new thread
}).Start();
}
这篇关于如何在C#中多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文