MusiGenesis
MusiGenesis

Reputation: 75396

.NET threading question

Is there any essential difference between this code:

ThreadStart starter = new ThreadStart(SomeMethod);
starter.Invoke();

and this?

ThreadStart starter = new ThreadStart(SomeMethod);
Thread th = new Thread(starter);
th.Start();

Or does the first invoke the method on the current thread while the second invokes it on a new thread?

Upvotes: 6

Views: 224

Answers (2)

Foole
Foole

Reputation: 4850

In case SLaks' answer is not totally clear:

does the first invoke the method on the current thread while the second invokes it on a new thread?

Yes.

Upvotes: 3

SLaks
SLaks

Reputation: 888187

They are not the same.

Calling new ThreadStart(SomeMethod).Invoke() will execute the method on the current thread using late binding. This is much slower than new ThreadStart(SomeMethod)(), which is in turn a little bit slower than SomeMethod().

Calling new Thread(SomeMethod).Start() will create a new thread (with its own stack), run the method on the thread, then destroy the thread.

Calling ThreadPool.QueueUserWorkItem(delegate { SomeMethod(); }) (which you didn't mention) will run the method in the background on the thread pool, which is a set of threads automatically managed by .Net which you can run code on. Using the ThreadPool is much cheaper than creating a new thread.

Calling BeginInvoke (which you also didn't mention) will also run the method in the background on the thread pool, and will keep information about the result of the method until you call EndInvoke. (After calling BeginInvoke, you must call EndInvoke)

In general, the best option is ThreadPool.QueueUserWorkItem.

Upvotes: 13

Related Questions