C# 中的线程和静态方法
下面是一个无意义的扩展方法作为示例:
public static class MyExtensions
{
public static int MyExtensionMethod(this MyType e)
{
int x = 1;
x = 2;
return x
}
}
假设一个执行线程完成并包括以下行:
x = 2;
然后处理器进行上下文切换,另一个线程进入相同的方法并完成该行:
int x = 1;
我假设变量“x”是正确的吗?第一个线程创建和分配的变量位于第二个线程创建和分配的变量“x”的单独堆栈上,这意味着该方法是可重入的?
Here is a meaningless extension method as an example:
public static class MyExtensions
{
public static int MyExtensionMethod(this MyType e)
{
int x = 1;
x = 2;
return x
}
}
Say a thread of execution completes upto and including the line:
x = 2;
The processor then context switches and another thread enters the same method and completes the line:
int x = 1;
Am I correct in assuming that the variable "x" created and assigned by the first thread is on a separate stack to the variable "x" created and assigned by the second, meaning this method is re-entrant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,每个线程都有自己单独的局部变量。即使被多个线程同时调用,该函数也始终返回 2。
Yes, each thread gets its own separate local variable. This function will always return 2 even if called by multiple threads simultaneously.
是的,这是一个正确的评估。
x
是方法局部变量,不会在MyExtensionMethod
的调用之间共享。Yes, that's a correct assessment.
x
is a method-local variable, and won't be shared between invocations ofMyExtensionMethod
.很简单,是的。静态方法仅意味着可以在没有对象的情况下调用该方法。方法内的局部变量仍然是局部的。
Quite simply, yes. A static method only means that the method can be called without an object. The local variables within the method are still local.