Skip to main content
 首页 » 编程设计

c#之如何在 c sharp 中的单个 com 端口同时接收多个任务

2024年02月24日20lidabo

我是 c sharp 的新手,我坚持执行此任务。我的要求是,我创建了许多线程,这些线程(使用 COM1 发送)必须与单个串行端口通信,比如 COM2。所有线程都必须使用单个 COM 端口发送消息(使用 COM2 接收)。

例如,使用 COM1 发送“helloworld1”(使用线程 1)和“helloworld2”(线程 2),并在 super 终端中使用 COM2 接收。所以我需要同时在 super 终端中看到两个 hell 世界。

请帮帮我。

请您参考如下方法:

由于您希望从两个不同的线程发送,因此您需要用锁{}包围您的调用 SerialPort.Write(),如下所示:

 
SerialPort s = new SerialPort(); 
 
//configure serial port, etc. 
 
//spin off additional threads 
 
//in each thread, do this: 
lock(s) 
{ 
  s.Write("Hello World1"); 
}