srikanth
srikanth

Reputation: 159

execute a C# method asynchronously using Threading

I have a method in a class that I need to execute twice asynchronously. The class has a constructor which accepts URL as a parameter :

ABC abc= new ABC(Url);

// Create the thread object, passing in the abc.Read() method
// via a ThreadStart delegate. This does not start the thread.
Thread oThread = new Thread(new ThreadStart(abc.Read());


ABC abc1= new ABC(Url2)

// Create the thread object, passing in the abc.Read() method
// via a ThreadStart delegate. This does not start the thread.
Thread oThread1 = new Thread(new ThreadStart(abc1.Read());

// Start the thread
oThread.Start();
// Start the thread
oThread1.Start();

Is this the way it works? Can anyone help?

Upvotes: 3

Views: 199

Answers (3)

David Hoerster
David Hoerster

Reputation: 28701

You can also do this:

Thread oThread1 = new Thread(() => abc1.Read());

You can pass a lambda in to the Thread constructor instead of newing up a new ThreadStart object.

Joseph Albahari has a great online resource about threading. Very easy to read and lots of examples.

Upvotes: 1

Ry-
Ry-

Reputation: 225164

Drop the parentheses to create a delegate:

Thread oThread = new Thread(new ThreadStart(abc.Read));

And do the same for oThread1. Here's MSDN's Delegates Tutorial.

Upvotes: 3

JaredPar
JaredPar

Reputation: 755357

You need to change your ThreadStart creation to use the method as a target instead of invoking the method

Thread oThread = new Thread(new ThreadStart(abc.Read);

Notice how I used abc.Read instead of abc.Read(). This version causes the ThreadStart delegate to point to the method abc.Read. The original version abc.Read() was invoking the Read method immediately and trying to convert the result to a ThreadStart delegate. This is likely not what you intended

Upvotes: 3

Related Questions