简体   繁体   English

从多个源调用静态方法时

[英]When a static method is called from multiple source

Lets say i have a static method with parameter in a class as shown : 可以说我在类中有一个带有参数的静态方法,如下所示:

 public static string NumberToLetter(int num)
{
    string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string Letter = String.Empty;
    //goes into loop using the parameter
    //does some logic
    return Letter;
}

Now what happens when this static method is called from other classes at a same time ? 现在,当同时从其他类中调用此静态方法时会发生什么?

Or in such a manner that when the first class called this method and starts executing and another class calls this static method when it is executing the first class request ? 还是以这样的方式,当第一个类调用此方法并开始执行,而另一个类在执行第一个类请求时调用此静态方法?

What will be the behavior ? 这将是什么行为? What will happen to the parameter value which is in loop? 循环中的参数值将如何处理?

The variables in this static method are local, so they will be created for each call. 此静态方法中的变量是局部变量,因此将为每个调用创建它们。 You will have n copies of these variables for n calls. 您将有n个调用的这些变量的n个副本。 Your parameter is not a reference type, so your parameter is also not shared. 您的参数不是引用类型,因此您的参数也不会共享。

Unless you share a variable/property/field in a method, multiple calls are thread safe, if that is what you mean. 除非您在方法中共享变量/属性/字段,否则多次调用是线程安全的。

Your function is static, your local variable is not. 您的函数是静态的,局部变量不是。 If there are no dependencies to outside static resources then it should work just fine. 如果没有对外部静态资源的依赖,那么它应该可以正常工作。

If would be totally different issue if you would be passing in a reference parameter or a mutable object. 如果要传递引用参数或可变对象,则完全不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM