CLR Threads and Windows Threads

weixin_34377065發表於2011-03-16

 Today, the CLR uses the threading capabilities of Windows, so Part V of this book is really focusing on how the threading capabilities of Windows are exposed to developers who write code by using the CLR. I will explain about how threads in Windows work and how the CLR alters the behavior (if it does). However, if you’d like more information about threads, I recommend reading some of my earlier writings on the topic, such as my book Windows via C/C++, 5th Edition (Microsoft Press, 2007).

While a CLR thread maps directly to a Windows thread today, the Microsoft CLR team reserves the right to divorce itself from Windows threads in the future. Someday, the CLR may introduce its own logical thread concept so that a CLR logical thread doesn’t necessarily map to a physical Windows thread. For example, there has been talk of creating logical threads that use much less resources than physical threads, and then you could have many logical threads running on top of a very small number of physical threads. For instance, the CLR could determine that one of your threads is in a wait state and reassign that thread to do a different task. The benefits of this include easier coding, less resources used, and potentially improved performance. Unfortunately, implementing this solution would be a huge amount of work for the CLR team, so I would not expect a feature like this to make it into the CLR anytime soon.

For you, all of this means that your code should make as few assumptions as possible when manipulating threads. For example, you should avoid P/Invoking to native Windows functions since these functions have no knowledge of a CLR thread.5 By avoiding native Windows functions and sticking with Framework Class Library (FCL) types whenever possible, you’re guaranteed that your code will easily take advantage of these performance enhancements as they become available in the future.

相關文章