none
why is static method thread safe natural.

    Question

  • I am confused on the title.

    Microsoft say their static method is thread safe in .net .

    question:1. only build-in static method is method?

                  2. we can custom static method without any lock or sync, it is thread safe natural.

     
    Friday, April 28, 2017 3:09 AM

All replies

  • I am confused on the title.

    Microsoft say their static method is thread safe in .net .

    question:1. only build-in static method is method?

                  2. we can custom static method without any lock or sync, it is thread safe natural.

     

    I don't believe that Microsoft actually says anywhere that their static methods are thread safe, can you cite a reference?

    A class is not somehow inherently thread-safe just because it is static.  Perhaps what you are referring to is the fact that static constructors are thread safe in that they execute only once.

    Here's a relevant passage from the C# Language Specification.

    The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

    • An instance of the class is created.
    • Any of the static members of the class are referenced.


    • Edited by Wyck Saturday, April 29, 2017 4:16 AM
    Friday, April 28, 2017 5:05 AM
  • Ironically static methods are the one type of code that is generally not thread safe by default. Unlike an instance method, static methods can only rely on the parameters their given and static fields. Static fields are shared by all threads and therefore must be made thread safe if the data is being changed.

    However most static methods don't actually modify any static fields, they simply work against the parameters they are passed and perhaps read static field values (that are generally set at creation). In this regard most static methods are naturally thread-safe because they aren't going to be changing the same data across threads (unless you're using the same arguments across threads but that is an entirely different story). Therefore most static methods can be identified as thread safe. The general rule of thumb is if a method only modifies parameter data then it is naturally thread safe.

    As a final note, there is a little used attribute that you can apply to a method to basically make it thread safe. But it does so by serializing all calls to the method such that only 1 thread can be calling it at a time. In the early .NET days it was used for some methods but I haven't seen it used since the v2 days.

    Michael Taylor
    http://www.michaeltaylorp3.net

    Friday, April 28, 2017 2:02 PM
    Moderator