Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 741
MusiGenesis Avatar asked Mar 15 '10 21:03

MusiGenesis


People also ask

Is .NET multi threaded?

With . NET, you can write applications that perform multiple operations at the same time. Operations with the potential of holding up other operations can execute on separate threads, a process known as multithreading or free threading.

Is .NET single threaded?

By default, a . NET program is started with a single thread, often called the primary thread. However, it can create additional threads to execute code in parallel or concurrently with the primary thread.

What is multithreading in C# Interview Questions?

Answer :A thread is basically a separate sequence of instruction designed to performing a " specific task" in the program. Question 2. What Is Multithreading In C# ? Answer :Performing multiple task at same time during the execution of a program,is known as multithreading.

What is threading in .NET framework?

Threads are tasks that can run concurrently to other threads and can share data. When your program starts, it creates a thread for the entry point of your program, usually a Main function.


2 Answers

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.

like image 52
SLaks Avatar answered Nov 15 '22 08:11

SLaks


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.

like image 25
Foole Avatar answered Nov 15 '22 08:11

Foole