c# Multithreaded – start thread with parameter and return value

When creating an application, you will face situations where you want to launch threads in order to keep the current process responsive. The System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The following codes shows how to launch a thread in different ways.


1. Starting A Thread

Regular Way

Thread thread = new Thread(new ThreadStart(MyFunction));
thread.Start();

Public void MyFunction() {}

Lambda Expression (C# 3.0 and above)

Thread thread = new Thread(() => MyFunction());
thread.Start();

Public void MyFunction() {}

2. Starting A Thread With Parameter

Regular Way

string parameterOne;
Thread t = new Thread (new ParameterizedThreadStart(MyFunction));
t.Start (parameterOne);

Public void MyFunction(string param) {}

Lambda Expression (C# 3.0 and above)

string param1 = "123";
int param2 = 321
Thread t = new Thread (() => MyFunction(param1, param2));
t.Start ();

Public void MyFunction(string param1, int param2) {}

3. Starting A Thread with Return Value

object value = null;
  Thread thread = new Thread(() => { value = MyFunction("Hello World") });
  thread.Start();
  thread.Join();

Public void MyFunction(string param1) {}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s