.NET thread question

Is there a significant 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 call the method in the current thread, and the second calls it in the new thread?

+6
multithreading c #
source share
2 answers

They do not match.

A call to new ThreadStart(SomeMethod).Invoke() will execute the method in the current thread using late binding. This is much slower than new ThreadStart(SomeMethod)() , which in turn is slightly slower than SomeMethod() .

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

A call to ThreadPool.QueueUserWorkItem(delegate { SomeMethod(); }) (which you did not mention) will start the method in the background in the thread pool, which is a set of threads automatically managed by .NET on which you can run the code. Using ThreadPool is much cheaper than creating a new thread.

A BeginInvoke call (which you also did not mention) will also run the method in the background in the thread pool and save the result information of the method until you name EndInvoke . (After calling BeginInvoke you should call EndInvoke )

In general, the best option is ThreadPool.QueueUserWorkItem .

+13
source share

In case the SLaks answer is not entirely clear:

Does the first method call the method in the current thread, and the second calls it in the new thread?

Yes.

+3
source share

All Articles