【问题标题】:Thread Safe Method?线程安全方法?
【发布时间】:2012-03-20 03:02:58
【问题描述】:

我有一个具有以下静态方法的类:

public static Content GetContentById(int id)
{
    Content c = null;

    string sql = "SELECT QUERY";

    using (SqlDataReader dr = SqlHelper.ExecuteReader(Constants.ConnectionString, CommandType.Text, sql, new SqlParameter("@id", id)))
    {
          if (dr.HasRows && dr.Read())
          {
               c = new Content(dr.GetInt32(0));
          }
    }

    return c;
 }

现在,我已经阅读了一些关于线程的内容,在我看来它应该是安全的,因为它只使用局部变量而不是在全局状态下操作对象/成员?

谁能帮我确认一下?

编辑:包含内容构造函数

    public Content(int Id)
    {
        this.Id = Id;
    }

【问题讨论】:

  • 你不认为 SQL Server 中的任何东西都是全局状态吗?
  • Content的构造函数发生了什么?
  • 我的构造函数只是将值分配给对象。

标签: c# multithreading methods static thread-safety


【解决方案1】:

假设 Content 的构造函数没有做任何令人惊讶的事情(阅读:多线程不安全),那么对我来说它看起来是线程安全的。

【讨论】:

    【解决方案2】:

    您只使用局部变量并且只对数据库进行读取。我认为这是安全的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      相关资源
      最近更新 更多