从实例方法线程安全调用静态方法吗?
Is calling a static method from an instance method thread safe?
在下面的例子中调用实例方法RenderHelp
是线程安全的吗?它调用 Helper
class 的静态方法,但不使用 class 的任何静态变量。
如果 Helper
的 2 个或更多不同实例(每个 运行 在不同的线程上)调用 RenderHelp
,是否会有 ever 成为问题?
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 或其他文档的链接。谢谢。
*另外,为什么 Whosebug 不能像上面那样正确地格式化 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.
如果您要在这些函数中的某处使用静态变量,那么它不会是线程安全的,除非您开始使用锁定或其他线程安全的方式来处理该变量。
在下面的例子中调用实例方法RenderHelp
是线程安全的吗?它调用 Helper
class 的静态方法,但不使用 class 的任何静态变量。
如果 Helper
的 2 个或更多不同实例(每个 运行 在不同的线程上)调用 RenderHelp
,是否会有 ever 成为问题?
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 或其他文档的链接。谢谢。
*另外,为什么 Whosebug 不能像上面那样正确地格式化 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.
如果您要在这些函数中的某处使用静态变量,那么它不会是线程安全的,除非您开始使用锁定或其他线程安全的方式来处理该变量。