Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

c# - Race Condition with Static Class?

Let's say I have a static class with a static method.

Multiple threads can call this static method concurrently.

Is there a potential for a race condition under these circumstances:

a - if the method depends only on local variables
b - if the method depends on local variables and member fields
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's say I have a static class with a static method. Multiple threads can call this static method concurrently.

OK.

Is there a potential for a race condition under these circumstances: a - if the method depends only on local variables

Yes, there are potential race conditions.

b - if the method depends on local variables and member fields

Yes, there are potential race conditions.

The answers to (a) and (b) are a consequence of a more general rule, namely, there is always the potential for race conditions any time you call any method from multiple threads. For example, this program deadlocks:

class MyClass
{
  static MyClass() 
  {
    // Let's run the initialization on another thread!
    var thread = new System.Threading.Thread(Initialize);
    thread.Start();
    thread.Join();
  }

  static void Initialize() 
  { }

  static void Main() 
  { }
}

It has no fields, two methods that do absolutely nothing, and a single local variable that is only accessed on a single thread. And nevertheless, it immediately and consistently deadlocks. (Do you see why? See http://ericlippert.com/2013/01/31/the-no-lock-deadlock/ for more on this program.)

It sounds like you are looking for a guarantee that your program is threadsafe if your static methods do not access fields. There is no such guarantee. Your program is threadsafe if and only if you write it to be threadsafe.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...