[英]C# equivalent of Java's synchronized (abc.class)
I would like to know if there is C# equivalent of the following Java code: 我想知道是否存在以下Java代码的C#等价物:
synchronized (abc.class) {
// code here
}
If there isn't an equivalent, then how can I simulate it in C#? 如果没有等价物,那我怎样才能在C#中模拟它?
abc
is a one of my classes in the program. abc
是我在该计划中的一个课程。 abc
properties and methods (some of them are static) are accesses by many threads at the same time. abc
属性和方法(其中一些是静态的)是许多线程同时访问的。 Do not block the class! 不要阻止班级! This may lead to very big problems in your code.
这可能会导致代码中出现很大问题。 Instead, use the
lock
construct to access static resources from your code: 相反,使用
lock
构造从代码中访问静态资源:
class Abc
{
private static object _resource;
static Abc()
{
_resource = new object();
}
public static void Method1()
{
lock (_resource)
{
// this will run for only one thread at a time
}
}
public static void Method2()
{
lock (_resource)
{
// this will run for only one thread at a time
}
}
}
Also, you may use the ReadWriteLock
( Slim
) for your synchronization, if one thread need only to read the resource without writing to it. 此外,如果一个线程只需要读取资源而不写入资源,则可以使用
ReadWriteLock
( Slim
)进行同步。
To lock the entire class, use the following: 要锁定整个类,请使用以下命令:
lock (typeof(abc))
{
// code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.