Reputation: 25
I am reading data from a Serial Port in C# as follows:
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
If the function DataReceivedHandler is computationally intensive, is there a way to make sure that when the next data is received it doesn't wait for the previous function to complete, rather it starts another instances of DataReceivedHandler with the new data?
Upvotes: 1
Views: 12067
Reputation: 516
Hmm, I don't think that answer from Gh0st22 is concurrently sound. First off, the DataReceivedHandler is already called from a thread pool internal to the serial port class. Second, I see no locking implemented or mentioned. The serial buffer is going to be a nightmare to handle so let's step back a bit.
Are you actually observing the problem that you are afraid will occur? See this great response that I have referenced many times:
If you absolutely must spin up another thread, consider reading in the available serial data and passing it in as an argument. Otherwise you are just making a huge mess for yourself and any future maintainer on the project.
Upvotes: 2
Reputation:
You can achieve this by using Threading (add using System.Threading;
)
public static void main(string[] args)
{
SerialPort mySerialPort = new SerialPort();
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
Thread thread = new Thread(thisClass.Worker);
thread.Start(sender, e);
}
public static void Worker(object sender, object ev)
{
SerialDataReceivedEventArgs e = (SerialDataReceivedEventArgs) ev;
// Put your code here
}
Advantages:
- When this method is called while work is being done, it will be allowed to finish
Drawbacks:
- The program will continue running, even after its closed, until all threads are finished
Upvotes: 1