Lock in properties, good approach?

前端 未结 3 1790
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 11:29

In my multithreading application I am using some variables that can be altered by many instances in the same time. It is weird but it has worked fine without any problem..but of

3条回答
  •  有刺的猬
    2021-02-19 11:56

    It's very rare when all you need is just set a single property. More often selectedClient.A = 5 will be a part of a much bigger logical operation, which involves several assignments/evaluations/etc. During that whole operation you'd rather prefer selectedClient to be in a consistent state and not to introduce deadlocks/race conditions. Therefore, it will be much better to expose SyncRoot property in your Client class and lock on that from the calling code:

    Client selectedClient = GetClient(...);
    
    lock(selectedClient.SyncRoot)
    {
        selectedClient.A = 5;
        selectedClient.B = selectedClient.A * 54;
    }
    

提交回复
热议问题