静态方法是否共享其局部变量&来自不同线程的并发使用期间会发生什么? [英] Does a static method share its local variables & what happens during concurrent usage from different threads?

查看:261
本文介绍了静态方法是否共享其局部变量&来自不同线程的并发使用期间会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#问题-我正在尝试确定是否可以使用静态方法,在该方法中确实有一些使用的局部变量.局部变量是否在方法的使用之间共享"?例如,如果从不同线程同时调用/使用静态方法,会发生什么情况?一个线程会阻塞,直到另一个线程完成吗?

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

但是,如果方法本身使用静态变量,则应该使用适当的MT保护.另外,您可能要调用的外部方法也必须安全...

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

这篇关于静态方法是否共享其局部变量&来自不同线程的并发使用期间会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆