开发者

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

开发者 https://www.devze.com 2023-01-11 03:55 出处:网络
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 \"shared\" across usages of th

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 "shared" across usages of the method? What happens for example if the stat开发者_如何转开发ic method is being called/used at the same time from different threads? Does one thread block until the other is complete etc?

Perhaps the generalised question is, in a threaded application, when should one "not" being using a static method?


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...


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.


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

You may be thinking of Static functions in VB.


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

精彩评论

暂无评论...
验证码 换一张
取 消