msdn: What is “Thread Safety”?

前端 未结 4 1055
太阳男子
太阳男子 2021-02-14 11:31

In many MSDN documents, this is written under the Thread Safety heading;

\"Any public static (Shared in Visual Basic) members of this type are thread safe. Any instanc

4条回答
  •  醉梦人生
    2021-02-14 12:19

    Eric Lippert has an excellent blog post about this. Basically it's somewhat meaningless on its own.

    Personally I don't trust MSDN too much on this front, when I see that boiler-plate. It doesn't always mean what it says. For example, it says the same thing about Encoding - despite the fact that we all use encodings from multiple threads all over the place.

    Unless I have any reason to believe otherwise (which I do with Encoding) I assume that I can call any static member from any thread with no corruption of global state. If I want to use instance members of the same object from different threads, I assume that's okay if I ensure - via locking - that only one thread will use the object at a time. (That's not always the case, of course. Some objects have thread affinity and actively dislike being used from multiple threads, even with locking in place. UI controls are the obvious example.)

    Of course, it becomes tricky if objects are being shared unobviously - if I have two objects which each share a reference to a third, then I may end up using the first two objects independently from different threads, with all the proper locking - but still end up corrupting the third object.

    If a type does advertise itself to be thread safe, I'd hope that it would give some details about it. It's easy if it's immutable - you can just use instances however you like without worrying about them. It's partially or wholly "thread-safe" types which are mutable where the details matter greatly.

提交回复
热议问题