Which features make a class to be thread-safe?

后端 未结 6 1390
太阳男子
太阳男子 2020-12-13 03:19

In MSDN some .NET classes described like this:

\"This type is thread safe.\"

or

\"Public static (Shared in Visual Basic) m

6条回答
  •  情深已故
    2020-12-13 03:32

    First of all, don't use lock(this).

    This can cause deadlocks. Because other code can lock that same object from outside the class' scope. You should create a local Object and use it as the class' lock.

    Second, thread safety is a complicated issue. There's tons of material about this on the web.

    As a rule of thumb, all public methods should be locked and thread safe for the class to be thread-safe.

提交回复
热议问题