Petr
Petr

Reputation: 7957

Static method and threads

I have put one question on MSDN forum but got two opposite answers. In general I am intersted how threading works with static classes. If my code calls this(below) static method from 10 threads at the same time, is it thread safe? I mean, how the code flows behind the scenes? Does every thread executes the code within itself (like I think it does with non-static classes) or it is different with static method and, because its static, all threads try to reach the code and collide? Thanks!

public static class A
{

    static void Method(object parameter)
    {
       SqlCeConnection = .....
    }
}

Link to MSDN question: Here

PS: I am sorry due to IE page errors I cannot click on "Add comment" or "Answer", Jon Skeet answer is good (as usually :)

Upvotes: 1

Views: 932

Answers (2)

Pawan Mishra
Pawan Mishra

Reputation: 7268

A nice example can be singleton pattern.In this all you need is a single instance for a given class and that can be made sure by making the constructor private and giving a static method or property to access the instance.Following code snippets highlight the same :-

class MyClass
{
private MyClass()
{

}

public static MyClass Instance
{
    get
    {
        lock(typeof(MyClass))
        {
            if(__instance == null)
                __instance = new MyClass();
        }
        return __instance;
    }
}

}

Since the "Instance" method is marked static(thread consistent access) , but in multi threaded envoirnment you need to manully take care of it(using lock).

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503729

It's exactly the same as with non-static classes. Being static doesn't affect anything really - except that static methods are generally expected to be thread-safe. They're not automatically thread-safe, but you should make sure that you implement them in a thread-safe manner.

If the code doesn't use any shared state, it should be fine. And yes, without any locking, all the threads can be executing the same method concurrently.

Upvotes: 6

Related Questions