It is very common to use a private static readonly object for locking in multi threading.
I understand that private reduces the entry points to the locking object by tightening the encapsulation and therefore access to the most essential.
But why static?
private static readonly object Locker = new object();
At the end the field is only used within my class only, and I could also just use this instead:
private readonly object Locker = new object();
Any comments?
UPDATE:
As an example I have pasted this code (just an example). I could use static or non-static locker on this and both would work fine. Considering the answer below I should be rather defining my locker like this?
private readonly object Locker = new object();
And here is the code:
private int _priceA;
private int _priceB;
private EventWaitHandle[] _waithandle;
private readonly IService _service;
//ctor
public ModuleAViewModel(IService service)
{
_service = service;
_modelA = new ModelA();
_waithandle = new ManualResetEvent[2];
_waithandle[0] = new ManualResetEvent(false);
_waithandle[1] = new ManualResetEvent(false);
LoadDataByThread();
}
private void LoadDataByThread()
{
new Thread(() =>
{
new Thread(() =>
{
lock (Locker)
{
_priceA = _service.GetPriceA();
}
_waithandle[0].Set();
}).Start();
new Thread(() =>
{
lock (Locker)
{
_priceB = _service.GetPriceB();
}
_waithandle[1].Set();
}).Start();
WaitHandle.WaitAll(_waithandle);
PriceA = _priceA;
PriceB = _priceB;
}).Start();
}
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…