考虑这段代码:
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/