c# - 从实例方法调用静态方法线程安全吗?

标签 c# .net multithreading c#-4.0 thread-safety

在下面的示例中调用实例方法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/

相关文章:

c# - .NET OpenFileDialog 是否可以设置为允许用户选择 .lnk 文件

java - 简单的 GUI 倒计时应该如何工作?

c# - SaveChanges 不适用于我的所有项目?

c# - EF6 - ExecuteSqlCommandAsync - 获取返回参数(声明标量变量错误)

c# - 将数百万条记录从 csv 文件插入 SQL Server 数据库的正确方法是什么?

C# ASP.NET WebApi 路由模板不适用于 uri 参数

.net - 无法在 WinDbg 中切换到托管线程

c# - CRUD 类库设计,返回有关业务逻辑失败的有用消息,这并不异常(exception)

java - future 取消不适用于多线程的 executorService

c++ - 如何使序列化并行运行