在下面的示例中调用实例方法RenderHelp
线程安全吗?它调用 Helper
类的静态方法,但不使用该类的任何静态变量。
如果 Helper
的 2 个或多个不同实例(每个实例在不同的线程上运行)调用 RenderHelp
,是否会出现问题?
public class Helper
{
public string ID { get; set; }
// other fields
static int[] Multiply(int[] a, int[] b)
{
if (a.Length == b.Length) return a.Zip(b, (a1, b2) => a1 * b2).ToArray();
else return null;
}
static int[] Add(int[] a, int[] b)
{
if (a.Length == b.Length) return a.Zip(b, (a1, b2) => a1 + b2).ToArray();
else return null;
}
public int[] RenderHelp(string help, int[]a, int[] b)
{
if (help == "Add".ToLower()) { return Add(a,b); }
else if (help == "Multiply".ToLower()) { return Multiply(a,b); }
else return null;
}
}
非常感谢相关 MSDN 或其他文档的链接。谢谢。
*另外,为什么 stackoverflow 没有正确格式化 get
,如上面所示?
最佳答案
是的,这是线程安全的。线程问题通常发生在共享资源周围,而您在这里不这样做。这是继Microsoft threading之后建议:
Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility for threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests.
如果您要在这些函数中的某个位置使用静态变量,那么除非您开始使用锁定或其他线程安全的方式来处理该变量,否则它不会是线程安全的。
关于c# - 从实例方法调用静态方法线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32373140/