有什么用SyncRoot上图案? [英] What's the use of the SyncRoot pattern?

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

问题描述

我读描述SyncRoot上图案的C#的书。它显示了

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

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

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

和比较S​​yncRoot上的模式:

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?

在此先感谢

推荐答案

如果您有想要prevent同时访问多个线程内部数据结构,你应该始终确保你锁定的对象在不公开。

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 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.

这意味着,最好的解决方法是使用内部对象,因此提示是只是使用对象

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天全站免登陆