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?
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.
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With