静态函数并发ASP.NET [英] Static Function Concurrency ASP.NET

查看:257
本文介绍了静态函数并发ASP.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有两个线程的时间在同一时刻调用静态函数,有没有并发风险?并且如果该函数使用类的静态成员,甚至有一个更大的问题?

If you have two threads invoking a static function at the same moment in time, is there a concurrency risk? And if that function uses a static member of the class, is there even a bigger problem?


  • 是彼此分开的两个电话? (功能就像是复制的两个线程?)

  • 难道他们会自动排队?

比如在下面的例子中,有没有风险呢?

For instance in next example, is there a risk?

private static int a = 5;

public static int Sum()
{
    int b = 4;
    a = 9;
    int c = a + b;
    return c;
}

和下一个例子,有没有风险呢?

And next example, is there a risk?

public static int Sum2()
{
   int a = 5;
   int b = 4;
   int c = a + b;
   return c;
}

更新:事实上,如果这两个功能都在同一个班,什么是风险,然后

Update: And indeed, if both functions are in the same class, what is the risk then?

THX,列文Cardoen

thx, Lieven Cardoen

推荐答案

对了,还有就是当你在静态方法修改静态变量并发风险。

Yes, there is a concurrency risk when you modify a static variable in static methods.

静态函数本身有不同的套本地变量,但任何静态变量是共享的。

The static functions themselves have distinct sets of local variables, but any static variables are shared.

在特定的样品你不被暴露,但是这只是因为你使用常量(和分配相同的值给他们)。稍微改变code样品,你会被暴露出来。

In your specific samples you're not being exposed, but that's just because you're using constants (and assigning the same values to them). Change the code sample slightly and you'll be exposed.

编辑:

如果你调用的两个的SUM1()和SUM2()从你就麻烦了不同的线程,有没有办法保证的这个说法和b的值:诠释三= A + b;

If you call both Sum1() AND Sum2() from different threads you're in trouble, there's no way to guarantee the value of a and b in this statement: 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;
}

您还可以实现并发问题多次调用的一个方法的是这样的:

You can also achieve concurrency problems with multiple invocations of a single method like this:

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;
}

这里的问题是,a的值会因其他调用更改它改变中期的方法。

The issue here is that the value of a may change mid-method due to other invocations changing it.

这篇关于静态函数并发ASP.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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