VB .NET Shared Function if called multiple times simultaneously

久未见 提交于 2019-12-10 17:16:43

问题


Consider I have a shared function:-

Public Shared Function CalculateAreaFromRadius(ByVal radius As Double) As Double

    ' square the radius...
    Dim radiusSquared As Double
    radiusSquared = radius * radius

    ' multiply it by pi...
    Dim result As Double
    result = radiusSquared * Math.PI

    'Wait a bit, for the sake of testing and 
    'simulate another call will be made b4 earlier one ended or such
     for i as Integer = 0 to integer.Max
     Next

    ' return the result...
    Return result

End Function

My Questions:

  1. If I have two or more threads in the same vb .net app and each of them calls the shared function at the same time with different RADIUS, will they each get their own AREA?

  2. I want to know for each call to the function if it is using same local variables or each call creates new instances of local variables?

  3. Will the answers to above questions be same If I have multiple (2+) single threaded apps and they all call the function at the same time with different RADIUS value?

I will appreciate your reponse. Thank you.


回答1:


1) If I have two or more threads in the same vb .net app and each of them calls the shared function at the same time with different RADIUS, will they each get their own AREA?

Yes, because the radius value is passed by value and the method uses nothing but locally declare variables.

2) I want to know for each call to the function if it is using same local variables or each call creates new instances of local variables?

Each call creates a new instance of its local variables.

3) Will the answers to above questions be same If I have multiple (2+) single threaded apps and they all call the function at the same time with different RADIUS value?

Yes. Again, because there is no shared storage of information and because all inputs are passed by value, it is thread-safe.




回答2:


The function uses no external state. It's only accessing its local variables so it's perfectly safe to call it from different threads.

  1. Yes
  2. Local variables are specific to the specific call regardless of the thread the function is running on (think about a recursive function; each time you call the function, it'll have a distinct set of local variables).
  3. Yes


来源:https://stackoverflow.com/questions/2519356/vb-net-shared-function-if-called-multiple-times-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!