gpt4 book ai didi

c# - 在多线程中调用静态方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:01 24 4
gpt4 key购买 nike

考虑这段代码:

public class Test
{
public void Print()
{
lock (this)
{
System.Threading.Thread.Sleep(10000);
Console.WriteLine("Print");
}
}
public static void Somthing()
{
Console.WriteLine("Somthing");
}
}

print 方法中,我lock 类并且 Somthing 是一个静态方法。我希望在 Print 之后调用 Somthing 时,Somthing 会单独运行线程,因为我没有 Test 的实例> 用于调用 Somthing

private static void Main(string[] args)
{
var test = new Test();
test.Print();
Test.Somthing();
}

但是当写上面的代码时,Test 被锁定然后调用Somthing

为什么编译器有这种行为?

最佳答案

这里没有任何东西会导致使用另一个线程;为什么会这样?你的代码:

  • 创建一个Test的实例>
  • 在该实例上调用 (callvirt) Print
    • 它自身有一个Monitor 锁(顺便说一句,这不是个好主意)
    • 睡了 10 秒
    • 向控制台写入一行
    • 释放Monitor
  • 调用(调用)静态Something方法
    • 向控制台写入一行

不需要额外的线程。我应该强调:即使您没有释放Monitor锁(通过使用Monitor.Enter而不一个 Monitor.Exit);再次:lock 不创建线程

lock 只是停止(阻止)other 线程在持续时间内lock同一对象 -它创建了一个相互排斥的区域。它不会创建线程。

关于c# - 在多线程中调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17918598/

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