views:

138

answers:

5

Hi all,

I'm developing a serial port communication application. I've written a class. In serial port's DataReceived event, I need to invoke a method to do some string operations. I want to make these operations in another thread.

But since my application is not a windows from application (it's a class only), it does not have the Invoke() method.

So, how can I invoke a method in a class which does not have Invoke() method?

Thanks

A: 

Use System.Threading.Thread class and pass your method through a delegate.

EDIT:

class Myclass
{

System.Threading.Thread t1 = new System.Threading.Thread(new ThreadStart(mymethod));

public void mymethod()
{
// do something here
}

public void ExecuteMyThread()
{
t1.Start();
}

}

class MainClass
{
Myclass mycl = new Myclass();

public static void Main(string args)
{
// start my thread from other class
mycl.ExecuteMyThread();
}
Tony
Can you explain a bit more? Thanks
UnforgivenX
+4  A: 

Am I understanding correctly that you want to call a method asynchronously? If so:

Thread.QueueUserWorkItem(myCallBack)

where myCallBack is a delegate eating an object and returning void. See MSDN where there's even a simple example.

Jason
A: 

You can create and run a new thread yourself:

Thread thread = new Thread(MyBackgroundMethod);

thread.Start();

...

public void MyBackgroundMethod()
{
 ...
}
Philippe Leybaert
+1  A: 

Since you are not dealing with UI, you don't need to use Invoke to synchronize. You can just spawn a new thread using the ThreadPool, a BackgroundWorker or just create a new Thread. You will need to apply some synchronization mechanism (such as lock or similar) if you from that thread access data that may be accessed from other threads as well.

Simple example:

// code in your class that reads data from serial port
string data = GetDataFromSerialPort();
ThreadPool.QueueUserWorkItem(DoSomeProcessing, data);    

private static void DoSomeProcessing(object state)
{
    string data = state.ToString();
    // process data
}
Fredrik Mörk
A: 

The easiest way is to use BackgroundWorker which is in the namespace System.ComponentModel.BackgroundWorker. It makes managing asynchronous operations on a background thread easy and handlers can be added to cancel, monitor progress and respond once the worker thread has completed. Here is the link on MSDN link text

Andrew