MathuSum Mut MathuSum Mut - 1 year ago 114
C# Question

Set thread exit code manually in C#?

Is there a way to set the thread exit code manually in C# (for debugging purposes)?

The selected answer of a related question "What is a thread exit code" states:


0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.


Is there really a way to set a thread's exit code myself?

Answer Source

.NET threads do not have exit codes. Those are used by the native threads on Windows, but native threads are only used by managed threads, and have no 1:1 correspondence to a given managed thread. The same managed thread can run on multiple native threads and vice versa (though obviously not at the same time). To quote MSDN:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the Fiber API to schedule many managed threads against the same operating system thread, or to move a managed thread among different operating system threads.

This of course applies to all resources tied to the native thread - but the runtime does manage the managed resources of a thread, of course; and for unmanaged code calling into managed code, the thread will be kept the same - otherwise interop would be quite impossible.

If you want to add extra information to tasks, try using a higher level of abstraction - e.g. Task. Need to output the status of a task on completion? Add a continuation. Need to check the status of a task you have a reference for? Await it or query the Task object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download