Harris M
Harris M

Reputation: 25

Serial Port Data Received Event Handler

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

Answers (2)

cory.todd
cory.todd

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:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/e36193cd-a708-42b3-86b7-adff82b19e5e/how-does-serialport-handle-datareceived?forum=netfxbcl#298028ff-2b76-4685-947c-f68291882b09

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

user4250079
user4250079

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

Related Questions