gpt4 book ai didi

c# - 如何在新线程中强制执行

转载 作者:行者123 更新时间:2023-11-30 20:11:14 25 4
gpt4 key购买 nike

我的应用程序中有这样的代码:

var t = new Thread(new ThreadStart(new Action(SomeClass.SomeMethod)));
t.Start();
...
t.Join();

但据我所知,编译器做了一些优化并在同一个线程中运行 SomeMethod作为主要代码。我通过在 t 和 Thread.CurrentThread 中设置不同的线程名称来检查这一点。我如何创建和运行线程以确保它是新线程。

最佳答案

编译器不会以这种方式优化您的代码。代码将在新的 .NET 线程中运行。您的观察方式一定有误。

请注意,.NET 线程不一定等同于操作系统线程:

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 CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

理论上您可以看到两个具有相同 Windows 线程 ID 的托管线程,但 Thread.Name 属性仍然不同(假设您最初将名称设置为两个不同的值)。

如果您可以将您使用的代码发布到您观察到某些东西在错误的线程中运行的地方,则可能会发现您犯了什么错误。

关于c# - 如何在新线程中强制执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4034571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com