c# - 我可以在 C# 中的一行上锁定(某物)吗?

标签 c# multithreading syntax locking

下面的 _otherThing 字段会被锁保护吗?

class ThreadSafeThing
{
    private readonly object _sync = new object();

    private SomeOtherThing _otherThing;

    public SomeOtherThing OtherThing { get { lock(_sync) return _otherThing; } }

    public void UpdateOtherThing(SomeOtherThing otherThing)
    {
        lock(_sync) _otherThing = otherThing;
    }
}

最佳答案

是的。

这与锁无关。 C# 程序是用语句表示的。使用 {} 将多个语句分组为一个 block 。 block 可以在允许单个语句的上下文中使用。请参阅 C# 语言规范第 1.5 节。

关于c# - 我可以在 C# 中的一行上锁定(某物)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1276401/

相关文章:

php - 从 PHP 代码创建触发器时出现语法错误

c++ - 哪个先执行,RAII还是函数返回值

c - 线程池如何在 C 中创建带队列的线程池?

syntax - 需要有关创建新 "standard"的建议/"language"

c# - UnobtrusiveJavaScriptEnabled Spark View 引擎

ios - 如何等待 findObjectsInBackgroundWithBlock(在 Parse 中)完成然后运行 ​​MainThread?

c# - "() =>"在 C# 中是什么意思?

javascript - 基于事件导航选项卡的动态 MVC Razor href

c# - 数据模板绑定(bind)垃圾邮件输出窗口出现错误 : Cannot find governing FrameworkElemen

c# - 无法在 Windows 11 上找到任何已安装的 .NET Core SDK(Visual Studio 代码)