简体   繁体   English

公共静态类线程中的非静态成员安全吗?

[英]Is non static members inside public static class thread safe?

Can you check this function for me. 你能帮我检查一下这个功能吗? Is it thread safe or not to be used. 它是线程安全的还是不被使用。 I am trying to understand how exactly public static classes are working. 我试图了解公共静态类的工作原理。

This function will be used to get userId of visitor from database by username. 此函数将用于通过用户名从数据库获取访问者的userId。 So many concurrent call may happen. 可能会发生许多并发调用。 Also would this be the best performance way and sql injection secure. 也将是最好的性能方式和sql注入安全。

ASP.net 4.0 - C# - MSSQL 2008 R2 - IIS 7.5 ASP.net 4.0-C#-MSSQL 2008 R2-IIS 7.5

using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;

public static class csGetUserId
{
    public static string srCommandText = "select UserId from tblUsersProfile where userName=@userName";

    public static string ReturnUserId (string srUserName)
    {
        string srUserId = "0";

        using (SqlConnection connection = new SqlConnection(DbConnection.srConnectionString))
        {
            try
            {
                SqlCommand cmd = new SqlCommand(srCommandText, connection);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@userName", srUserName);
                SqlDataReader dsReader = null;
                connection.Open();
                dsReader = cmd.ExecuteReader();
                if (dsReader.HasRows)
                {
                    while (dsReader.Read())
                    {
                        srUserId=dsReader["UserId"].ToString();
                    }
                }
                else
                {

                }
            }
            catch
            {
                srUserId="-1";
            }
        }
        return srUserId;
    }
}

Assuming that the database supports multiple connections and that you change srCommandText to be readonly then this method is thread safe. 假设数据库支持多个连接,并且您将srCommandText更改为只读,则此方法是线程安全的。 Making srCommandText read-only will also make it safe against SQL injections. 将srCommandText设置为只读也可以防止SQL注入。

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

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