Threading and static methods in C#

2019-04-04 16:50发布

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?

3条回答
Melony?
2楼-- · 2019-04-04 16:54

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.

查看更多
萌系小妹纸
3楼-- · 2019-04-04 17:09

Yes, that's a correct assessment. x is a method-local variable, and won't be shared between invocations of MyExtensionMethod.

查看更多
闹够了就滚
4楼-- · 2019-04-04 17:11

Yes, each thread gets its own separate local variable. This function will always return 2 even if called by multiple threads simultaneously.

查看更多
登录 后发表回答