Why Locking On a Public Object is a Bad Idea

后端 未结 5 1700
时光取名叫无心
时光取名叫无心 2020-12-10 12:36

Ok, I\'ve used locks quite a bit, but I\'ve never had this scenario before. I have two different classes that contain code used to modify the same MSAccess database:

<
5条回答
  •  不知归路
    2020-12-10 13:07

    The reason it's bad practice to lock on a public object is that you can never be sure who ELSE is locking on that object. Although unlikely, someone else someday can decide that they want to grab your lock object, and do some process that ends up calling your code, where you lock onto that same lock object, and now you have an impossible deadlock to figure out. (It's the same issue for using 'this').

    A better way to do this would be to use a public Mutex object. These are much more heavyweight, but it's much easier to debug the issue.

提交回复
热议问题