How to receive multiple tasks at the same time in a single com port in c sharp
Im a novice in c sharp and im stuck with this task. My requirement is , I create many threads and these threads (send using COM1) have to communicate with a singl开发者_C百科e serial port say COM2. All the threads have to send message using a single COM port(receive using COM2).
say,send "helloworld1"(using thread1) and "helloworld2"(thread2) using COM1 and receive using COM2 in hyperterminal. So i need to see both the helloworlds in the hyperterminal at the same time.
Please help me out.
Since you want to send from two different threads, you will need to surround your calls SerialPort.Write() with a lock{} like this:
SerialPort s = new SerialPort();
//configure serial port, etc.
//spin off additional threads
//in each thread, do this:
lock(s)
{
s.Write("Hello World1");
}
You will want to start here.
You can instantiate 2 instances the SerialPort class for each COM port you want to send/receive on.
I have used 2 variations of receiving data us the SerialPort class:
1. You can manually "Read" on the port at a certain interval (e.g. you can have each thread read as needed).
2. The SerialPort class exposes a DataReceived event that can be subscribed to (an ErrorReceived is also available).
Option 1 might be the best fit.
Edit
After reading your comment, Option 2 may be a better fit so that you can have one "receive" thread that subscribes to the DataReceived/ErrorReceived events. Per @Slider, the lock will also be required to ensure only 1 thread is writing at any given time.
精彩评论