Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 221
Hex440bx Avatar asked Apr 11 '11 23:04

Hex440bx


1 Answers

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

like image 69
nitzmahone Avatar answered Nov 15 '22 10:11

nitzmahone