在 C# 中手动设置线程退出代码?

Set thread exit code manually in C#?

有没有办法在 C# 中手动设置线程退出代码(用于调试目的)?

相关问题“What is a thread exit code?”的选定答案指出:

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.

真的自己设置线程退出代码的方法吗?

.NET 线程没有退出代码。这些由 Windows 上的本机线程使用,但本机线程仅由托管线程 使用,并且与给定的托管线程没有 1:1 对应关系。同一个托管线程可以 运行 在多个本机线程上,反之亦然(尽管显然不是同时)。引用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.

这当然适用于绑定到本机线程的所有资源 - 但是 运行time 确实管理线程的 managed 资源,当然;对于调用托管代码的非托管代码,线程将保持不变 - 否则互操作将是完全不可能的。

如果您想向任务添加额外信息,请尝试使用更高级别的抽象 - 例如Task。需要在完成时输出任务状态?添加续集。需要检查您有参考的任务的状态?等待它或查询 Task 对象。