开发者

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜