java的synchronized关键字的C#版本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/541194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:25:14  来源:igfitidea点击:

C# version of java's synchronized keyword?

c#javamultithreadingsynchronization

提问by Soraz

Does c# have its own version of the java "synchronized" keyword?

c# 是否有自己版本的 java“同步”关键字?

I.e. in java it can be specified either to a function, an object or a block of code, like so:

即在 Java 中,它可以指定为函数、对象或代码块,如下所示:

public synchronized void doImportantStuff() {
   // dangerous code goes here.
}

or

或者

public void doImportantStuff() {
   // trivial stuff

   synchronized(someLock) {
      // dangerous code goes here.
   }
}

采纳答案by Marc Gravell

First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).

首先 - 大多数类永远不需要是线程安全的。使用YAGNI:仅当您知道您确实要使用它(并测试它)时才应用线程安全。

For the method-level stuff, there is [MethodImpl]:

对于方法级的东西,有[MethodImpl]

[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}

This can also be used on accessors (properties and events):

这也可以用于访问器(属性和事件):

private int i;
public int SomeProperty
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    get { return i; }
    [MethodImpl(MethodImplOptions.Synchronized)]
    set { i = value; }
}

Note that field-like events aresynchronized by default, while auto-implemented properties are not:

请注意,字段类事件默认同步的,而自动实现的属性不是

public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized

Personally, I don't like the implementation of MethodImplas it locks thisor typeof(Foo)- which is against best practice. The preferred option is to use your own locks:

就个人而言,我不喜欢实现MethodImplas it locksthistypeof(Foo)- 这违反了最佳实践。首选选项是使用您自己的锁:

private readonly object syncLock = new object();
public void SomeMethod() {
    lock(syncLock) { /* code */ }
}

Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this)/ lock(Type)- however, in more recent compilers it uses Interlockedupdates - so thread-safe without the nasty parts.

请注意,对于类似字段的事件,锁定实现取决于编译器;在较旧的 Microsoft 编译器中,它是lock(this)/ lock(Type)- 但是,在较新的编译器中,它使用Interlocked更新 - 因此线程安全,没有讨厌的部分。

This allows more granular usage, and allows use of Monitor.Wait/Monitor.Pulseetc to communicate between threads.

这允许更细粒度的使用,并允许使用Monitor.Wait/ Monitor.Pulseetc 在线程之间进行通信。

A related blog entry(later revisited).

一个相关的博客条目(后来重新访问)。

回答by Konrad Rudolph

Does c# have its own version of the java "synchronized" keyword?

c# 是否有自己版本的 java“同步”关键字?

No. In C#, you explicitly lockresources that you want to work on synchronously across asynchronous threads. lockopens a block; it doesn't work on method level.

否。在 C# 中,您可以明确指定lock要跨异步线程同步处理的资源。lock打开一个块;它在方法级别不起作用。

However, the underlying mechanism is similar since lockworks by invoking Monitor.Enter(and subsequently Monitor.Exit) on the runtime. Java works the same way, according to the Sun documentation.

但是,底层机制是相似的,因为lock通过在运行时调用Monitor.Enter(以及随后的Monitor.Exit)来工作。根据Sun 文档,Java 的工作方式相同。

回答by Jan Gressmann

static object Lock = new object();

lock (Lock) 
{
// do stuff
}

回答by James

You can use the lockstatement instead. I think this can only replace the second version. Also, remember that both synchronizedand lockneed to operate on an object.

您可以改用该lock语句。我认为这只能替代第二个版本。另外,请记住,synchronized和 都lock需要对一个对象进行操作。

回答by Traubenfuchs

Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)]should look like

请注意,完整路径的行:[MethodImpl(MethodImplOptions.Synchronized)]应该看起来像

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]