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?
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 thannew ThreadStart(SomeMethod)(), which is in turn a little bit slower thanSomeMethod().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 callEndInvoke. (After callingBeginInvoke, you must callEndInvoke)In general, the best option is
ThreadPool.QueueUserWorkItem.