1

I have a class A with helper static method aA. Local variables of this methods are static, I also instantiate an object B in it. Imagine that I create a few class A objects, calling this static method when necessary.

In real world I download asynchronously XML documents and parse them. Parse method is static and I wonder what is going on inside? Is such helper method thread safe? What is going on with static method variables?

Would you be so kind and explain how static method of instantiated class behaves in multi-threading environment?

2
  • 3
    Note that "Local variables of this methods are static" is likely not true as it very hard to achieve that in C# (there is no static local variables unlike C/C++). Commented Aug 29, 2013 at 18:38
  • Alexei you are right. Static variables of a non static class. Commented Aug 29, 2013 at 18:46

3 Answers 3

4

The answer is the same as with any other threading question of this nature: if the method is going to access mutable shared state, synchronize access to that state. This applies equally to static methods as it does to instance methods.

If the static method uses only its arguments and local variables (variables declared within the body of the method), then it is probably thread-safe. If it writes to static class-level variables or data structures, or reads from said structures if they can be mutated by another thread, then you must synchronize access to that data.

Without seeing the definition of the method in question, I cannot definitively state if that method is thread-safe.

Sign up to request clarification or add additional context in comments.

Comments

1

A method being static or not has no relationship at to whether it is thread-safe or not. An instance method is just a static method that takes a hidden parameter called this. No other difference.

Thread-safety is a property of the whole system, not of single methods. Make sure you do not write to variables that are being read or written in other threads at the same time. Make sure the system as a whole behaves to spec in the face of arbitrary thread scheduling.

Hard to say more without seeing code.

Comments

0

Static methods are not necessarily thread-safe, but they can be. Check the documentation on the particular method to see whether it's thread safe or not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.