0

Imagine a static method called foo() that is taking a considerable amount of time to execute. This method is inside a static class.

public static class FooClass
{
   public static void Foo()
   {
      Thread.Sleep(120000); // 2 minutes.
   }
}

I have a two instances of the same class that are calling this method concurrently. Since the FooClass is static, does that mean that Instance2 has to wait for Instance1 to finish executing foo() (given that Instance1 entered foo() first)?

From my knowledge, static classes contains one instance that is shared across the application pool.

4
  • You are mixing up static classes and static methods. Also, your code doesn't compile as you have non-static method in static class. Commented May 25, 2017 at 10:16
  • @Euphoric, can you please elaborate why I am mixing up static classes and static methods? Commented May 25, 2017 at 10:20
  • @kidra.pazzo - Dmitry fixed it for you but you had public void Foo() instead of public static void Foo() which would not compile as FooClass was marked as static. Commented May 25, 2017 at 10:27
  • Ah my apologies Commented May 25, 2017 at 10:28

2 Answers 2

2

No, they do not have to wait. Both threads can enter Foo at the same time and in the code above each thread will sleep for 2 minutes.

The only way to make one thread wait on another is to add a synchronization / locking mechanism like the lock keyword, or tyes Mutex or Monitor (to name a few).

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

2 Comments

Is it because the methods are reentrant?
@kidra.pazzo - No. The same is true of an instance method, they could also be accessed simultaneously by multiple threads. Threads and instance/static members have no direct relation to each other.
0

The same method can run on two threads at the 'same time', so both threads will sleep. If you need to ensure the method is atomic for each call (if it was editing data) you need to use a lock.

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.