views:

137

answers:

3

Hello everybody. We are developing a library in C# that communicates with the serial port. We have a function that is given to a delegate. The problem is that we want it to be run in a different thread.

We tried creating a new thread (called DatafromBot) but keep using it as follows (first line):

        comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);

        DatafromBot = new Thread(comPort_DataReceived);
        DatafromBot.Start();

comPort_DataReceived is defined as:

    Thread DatafromBot;
    public void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) {  ... }

The following errors occur:

Error 3 The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' has some invalid arguments C:...\IR52cLow\CommunicationManager.cs 180 27 IR52cLow

Error 4 Argument '1': cannot convert from 'method group' to 'System.Threading.ThreadStart' C:...\IR52cLow\CommunicationManager.cs 180 38 IR52cLow

Any ideas of how we should convert this to get it to compile? Please note that comPort.DataReceived (pay attention to "." instead of "_") lies within a system library and cannot be modified.

Thanks for your time! Chris

A: 
new Thread(() => comPort_DataReceived(null, null));

You could also pass the arguments sender and eventargs:

var e = new SerialDataReceivedEventArgs();
new Thread(() => comPort_DataReceived(comPort, e));
Darin Dimitrov
+1  A: 

Every Delegate has a method called BeginInvoke(). when called this method invokes the function on new thread. so you dont have to do it explicitly. For Eg.

Public delegate string delegate1 ( int x);

Delegate1 d1 = new Delegate1(Add);

D1.BeginInvoke(10, null, null);

Here Add method runs on a secondary thread. Primary thread continue with its operation and does not wait for the secondary thread to end. The primary thread will not come to know when the secondary thread has ended.

If you need notification when the method is complete, then you can you AsyncCallback class.

D1.BeginInvoke(10, AsyncCallback(AddComplete), null);

Here when secondary thread completes execution it invokes AddComplete() method on its thread. The primary thread does not wait for the secondary thread.

Check MSDN.

isthatacode
+1  A: 

This is not okay, the DataReceived event is triggered when the SerialPort receives something. You cannot just start a thread and hope that there will be something to read from the port.

More to the point, the DataReceived event already runs on a separate thread. The SerialPort class uses a threadpool thread to run the event. Using your own thread to read data from the port is okay but then you don't want to use DataReceived. You simply use the blocking calls, any of the ReadXxx() methods qualify.

Hans Passant