What's the proper way to wait for a .NET thread to start up?

霸气de小男生 提交于 2019-12-24 01:44:11

问题


I was reading the following on Microsoft's website within their threading tutorial:

http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

MSDN suggests using the following to wait for a thread to become alive:

while (!oThread.IsAlive);

Is this the recommended way to wait? Would it be better to insert a "DoEvents" call to allow the main thread to remain responsive? How should error handling be done in case something goes wrong and the thread never comes "alive?" If this is bad practice, when is IsAlive best used?

A few moderators have marked this as a duplicate, but the other question they reference doesn't mention anything about IsAlive, DoEvents, or proper error handling if the thread fails to start. My question is specifically related to the MSDN article I linked to within my question and its suggestion to use a busy loop with IsAlive.


回答1:


Seeing as there is no official answer yet... What you have seen on MSDN is from 2003, this is relatively old technology. For what you want to do I would use the Task Parallel Library (TPL). This requires .NET Framwork 4.0+.

For a great tutorial on how to use the TPL for what you require see:

  1. Task Parallel 1 of n.

  2. J. Albahari's Threading in C#.

Once you get to grips with TPL, feel free to come back and look for ask particular questions.

I hope this helps.




回答2:


In addition to Killercam's answer I want to point out that the sample code on the page linked is garbage. It looks like someone was told "create a sample that just shows all the different methods that we have on one page". And it literally came out like that...

When doing threading you almost never wait in a polling loop. Especially not in a tight one with any kind of waiting. They make the CPU hot, are unreliable, have high latency if you put a sleep in there and there are just better ways to do it. Spin loops are for experts who know what they're doing in very specific cases.

There is no point in waiting for a Thread to be "alive". Why would anyone do this in real code? This does not even mean that your thread proc has started executing (really! it doesn't.).

I recommend you use modern paradigms. The TPL is a good place to start. See Killercam's answer.



来源:https://stackoverflow.com/questions/15770538/whats-the-proper-way-to-wait-for-a-net-thread-to-start-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!