What's the equivalent of ExitThread(ExitCode) and GetExitCodeThread in C# & .net?

怎甘沉沦 提交于 2020-01-03 17:23:27

问题


Reading the VS2008 help file I've figured out that the clean way of exiting a thread (in .net) is either by using a return statement (in C#) or letting the thread reach the end of the method.

However, I have not found a method or property that would allow me to set the thread's exit code nor a way to retrieve it (as it is done using the Win32 API). Therefore, the question is, how do I do this using C# and .net ?

Thank you for your help,

John.


回答1:


The reason the underlying Win32 thread primitives aren't exposed is to prevent managed code from relying on them. The CLR team is always working on ways to optimize thread usage, and that includes no guarantees about 1:1 managed:unmanaged thread mapping (see "Note" on this MSDN page, for instance). If you really want to do it anyway, you'll need to set up P/Invoke wrappers that use an unmanaged thread handle from Win32 GetCurrentThread(), or hook into the thread mapping process yourself with a custom host. I wouldn't recommend either, unless you absolutely have to interop with something that uses thread exit codes and isn't managed code-aware. Figure out another way to smuggle state info around if you can do it all managed (or use Task Parallel Library to abstract up a level from bare threads).



来源:https://stackoverflow.com/questions/5628908/whats-the-equivalent-of-exitthreadexitcode-and-getexitcodethread-in-c-sharp

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