Does a static method share its local variables & what happens during concurrent usage from different threads?

后端 未结 4 1744
故里飘歌
故里飘歌 2021-01-17 15:21

C# Question - I\'m trying to determine whether it is OK to use a static method where, within the method it does have some local variables it uses. Are the local variables \

相关标签:
4条回答
  • 2021-01-17 15:41

    No method of any kind in C# shares local variables.

    You may be thinking of Static functions in VB.

    0 讨论(0)
  • 2021-01-17 15:41

    There are plenty of reasons to use static methods in multi-threaded apps. Nothing wrong with that either. As long as you do not change any global variables (without locking) you should have no problems there.

    0 讨论(0)
  • 2021-01-17 15:48

    Local variables within the method live on the stack and each thread has its own stack. Therefore it's safe for multiple threads to use the method.

    However if the method itself uses static variables then you should use appropriate MT protection. Also external methods you may be calling need to be safe...

    0 讨论(0)
  • 2021-01-17 15:57

    Are the local variables "shared" across usages of the method?

    No, they are not. Each thread executing the method has its own copy of the local variables, and they are independent of each other. When the method returns, the particular copy of locals for that particular thread is discarded. (*)

    What happens for example if the static method is being called/used at the same time from different threads? Does one thread block until the other is complete etc?

    No, they don’t; they will just execute the method on two separate stacks at the same time. If you actually want them to block, use the lock statement, which causes the second thread that enters the lock statement to wait until the first one returns from the lock statement. This may be necessary if your method accesses (non-local) fields, which are shared data.

    In a threaded application, when should one not use a static method?

    Whether you should use a static method or not depends on whether the method requires an object to operate on, but has nothing to do with whether your application is multi-threaded or not. For the purpose of threading, a static method is nothing special compared to a non-static method.

    (*) This may no longer be true if you have a lambda expression or anonymous method inside the method that uses the local variables, but this is a technicality.

    0 讨论(0)
提交回复
热议问题