Reputation: 7215
Background: we are developing an application (or windows service) that will listen for communications from various devices connected via virtual serial ports. Each device's information will be captured manually, so I know device 1 will be on COM5, Device 2 is on COM6, etc. Any time a device transmits data, I need to capture it and write in somewhere else (basically a log file).
With that in mind, is it possible to monitor more than one serial port on a single thread, or should I spawn a new thread for each port (keep in mind that I know exactly which ports to monitor)?
Or what would you guys think is a good approach?
My working prototype code looks like this (only reads one port though):
class Program
{
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM5");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine(indata);
Debug.Print("Data Received:");
Debug.Print(indata);
}
}
I'm basically wondering if I should create a class for each port that contains the code in the console application, or if I should go old-school and write a giant procedural app that monitors all of them at once.
Upvotes: 2
Views: 2903
Reputation: 1964
If the COM port devices are all similar, one class to handle retrieving their data with an instance for each device seems like the way to go. If separate functionality is needed you can always inherit from a base class. If you go down the rout of 'writing a giant procedural app' it will be much more difficult to maintain and modify in future.
As for multiple threads, the event handler you are using should allow multiple ports to be read without affecting other operations in your program. They can be considered their own thread, operations between them need to be handled as cross thread operations (such as changing form properties).
Upvotes: 1
Reputation: 39500
The DataReceived events tend to occur on a background thread created by SerialPort anyway.
This means: a. You don't need to create multiple threads yourself to monitor multiple ports b. You need to be careful what you do in the event handler, because you're probably not on your app's main thread, which can be a problem if, for example, you interact directly with a window. Your console stuff will be fine, however.
Upvotes: 1