什么是读/写在一个类C#属性线程安全的方法是什么? [英] What is a thread-safe way to read/write a C# property in a class?

查看:441
本文介绍了什么是读/写在一个类C#属性线程安全的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#。在Java中,我可以通过在二传手/ getter方法'同步'关键字读一个Java类成员/写。

I am new to C#. In Java, I can make read/write of a Java class member by having 'synchronized' keyword in the setter/getter method.

能否请你告诉我什么是正确的方式做在C#中的一样吗?在C#中没有synchronized关键字。我应该使用在 C#版本中提到[MethodImpl(MethodImplOptions.Synchronized)]注释 Java的synchronized关键字?

Can you please tell me what is the right way to do the same in C#? In C# there is no synchronized keyword. Should I use '[MethodImpl(MethodImplOptions.Synchronized)] annotation' mentioned in C# version of java's synchronized keyword??

或使用Monitor.Enter(随后Monitor.Exit)?

Or use Monitor.Enter (and subsequently Monitor.Exit)?

推荐答案

使用 Monitor.Enter / 退出(或 锁定 - 一个语法糖为显示器)使用私有对象_lock =新的对象()字段。

Use Monitor.Enter/Exit (or lock - a syntactic sugar for Monitor) with private object _lock = new object() field.

不要使用的 MethodImplOptions.Synchronized 。它锁定在这个,所以它可能是一些其他的代码将锁定在同一实例导致死锁。

Don't use MethodImplOptions.Synchronized. It locks on this, so it's possible that some other code will lock on the same instance causing deadlocks.

锁定在实例或类型,与同步标志,不建议用于公共类型,因为不是您自己的代码可以采取公共类型和实例锁。这可能会导致死锁或其他同步问题。

Locking on the instance or on the type, as with the Synchronized flag, is not recommended for public types, because code other than your own can take locks on public types and instances. This might cause deadlocks or other synchronization problems.

这篇关于什么是读/写在一个类C#属性线程安全的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆