SyncRoot 模式有什么用? [英] What's the use of the SyncRoot pattern?

查看:14
本文介绍了SyncRoot 模式有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一本描述 SyncRoot 模式的 C# 书籍.它显示

I'm reading a c# book that describes the SyncRoot pattern. It shows

void doThis()
{
    lock(this){ ... }
}

void doThat()
{
    lock(this){ ... }
}

并与 SyncRoot 模式进行比较:

and compares to the SyncRoot pattern:

object syncRoot = new object();

void doThis()
{
    lock(syncRoot ){ ... }
}

void doThat()
{
    lock(syncRoot){ ... }
}

然而,我不太明白这里的区别;似乎在这两种情况下,这两种方法一次只能由一个线程访问.

However, I don't really understand the difference here; it seems that in both cases both methods can only be accessed by one thread at a time.

书中描述了...因为实例的对象也可以用于从外部同步访问而你不能控制这种形式的类本身,你可以使用SyncRoot模式诶?'实例对象'?

The book describes ... because the object of the instance can also be used for synchronized access from the outside and you can't control this form the class itself, you can use the SyncRoot pattern Eh? 'object of the instance'?

谁能告诉我上面两种方法的区别?

Can anyone tell me the difference between the two approaches above?

推荐答案

如果您想要防止多个线程同时访问一个内部数据结构,您应该始终确保您锁定的对象不是公开.

If you have an internal data structure that you want to prevent simultaneous access to by multiple threads, you should always make sure the object you're locking on is not public.

这背后的原因是任何人都可以锁定公共对象,因此您可能会创建死锁,因为您无法完全控制锁定模式.

The reasoning behind this is that a public object can be locked by anyone, and thus you can create deadlocks because you're not in total control of the locking pattern.

这意味着锁定 this 不是一种选择,因为任何人都可以锁定该对象.同样,你不应该锁定你暴露给外界的东西.

This means that locking on this is not an option, since anyone can lock on that object. Likewise, you should not lock on something you expose to the outside world.

这意味着最好的解决方案是使用内部对象,因此建议只使用Object.

Which means that the best solution is to use an internal object, and thus the tip is to just use Object.

锁定数据结构是您真正需要完全控制的事情,否则您可能会面临设置死锁场景的风险,这可能会非常难以处理.

Locking data structures is something you really need to have full control over, otherwise you risk setting up a scenario for deadlocking, which can be very problematic to handle.

这篇关于SyncRoot 模式有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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