日期:2014-05-18 浏览次数:21338 次
此时,只有执行 Main 的主线程还存在。它会显示一条最终消息,然后返回,从而使主线程也终止。 下面显示了完整的示例: using System; using System.Threading; public class Worker { // This method will be called when the thread is started. public void DoWork() { while (!_shouldStop) { Console.WriteLine("worker thread: working..."); } Console.WriteLine("worker thread: terminating gracefully."); } public void RequestStop() { _shouldStop = true; } // Volatile is used as hint to the compiler that this data // member will be accessed by multiple threads. private volatile bool _shouldStop; } public class WorkerThreadExample { static void Main() { // Create the thread object. This does not start the thread. Worker workerObject = new Worker(); Thread workerThread = new Thread(workerObject.DoWork); // Start the worker thread. workerThread.Start(); Console.WriteLine("main thread: Starting worker thread..."); // Loop until worker thread activates. while (!workerThread.IsAlive); // Put the main thread to sleep for 1 millisecond to // allow the worker thread to do some work: Thread.Sleep(1); // Request that the worker thread stop itself: workerObject.RequestStop(); // Use the Join method to block the current thread // until the object's thread terminates. workerThread.Join(); Console.WriteLine("main thread: Worker thread has terminated."); } }
------解决方案--------------------
线程new后有个ManagedThreadId,可以用来区分,不过注意因为是托管线程,和本地线程是不一样的,是一对多的关系
It is not possible to use ManagedThreadId in this context. This is a completely managed concept and has no real representation in the native world. Hence it doesn't make any sense to the API's you're passing it to.
The reason ManagedThreadId exists is because there is not necessarily a 1-1 mapping between a native and managed thread. The CLR is free to use multiple native threads to run a single managed thread as long as the native thread is compatible with the one it's replacing. It cannot for instance, be in a different COM apartment.
In some ways you're a bit stuck here. AFAIK, there is no way to 100% guarantee that you will have the same native thread for a given managed thread. You can achieve a very high level of guarante