Lie*_*oen 6 c# asp.net concurrency static
如果你有两个线程在同一时刻调用静态函数,是否存在并发风险?如果该函数使用类的静态成员,是否还有更大的问题?
例如,在下一个例子中,是否存在风险?
private static int a = 5;
public static int Sum()
{
int b = 4;
a = 9;
int c = a + b;
return c;
}
Run Code Online (Sandbox Code Playgroud)
接下来的例子,是否存在风险?
public static int Sum2()
{
int a = 5;
int b = 4;
int c = a + b;
return c;
}
Run Code Online (Sandbox Code Playgroud)
更新:事实上,如果两个函数属于同一个类,那么风险是什么?
thx,Lieven Cardoen
kro*_*old 10
是的,在静态方法中修改静态变量时存在并发风险.
静态函数本身具有不同的局部变量集,但是共享任何静态变量.
在您的特定样本中,您没有被暴露,但这只是因为您正在使用常量(并为它们分配相同的值).稍微更改代码示例,您将被暴露.
编辑:
如果调用这两个 SUM1()和你就麻烦了不同的线程SUM2(),有没有办法保证的这个说法和b的值: INT C = A + B;
private static int a = 5;
public static int Sum1()
{
int b = 4;
a = 9;
int c = a + b;
return c;
}
public static int Sum2()
{
int b = 4;
int c = a + b;
return c;
}
Run Code Online (Sandbox Code Playgroud)
您还可以通过多次调用单个方法来实现并发问题,如下所示:
public static int Sum3(int currentA)
{
a = currentA;
int b = 4;
int c = a + b;
int d = a * b; // a may have changed here
return c + d;
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是a的值可能会因为其他调用改变它而改变中间方法.
| 归档时间: |
|
| 查看次数: |
4423 次 |
| 最近记录: |