简体   繁体   中英

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. So many concurrent call may happen. Also would this be the best performance way and sql injection secure.

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. Making srCommandText read-only will also make it safe against SQL injections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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