Furkan Gözükara
Furkan Gözükara

Reputation: 23870

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;
    }
}

Upvotes: 0

Views: 324

Answers (1)

Erel
Erel

Reputation: 1802

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.

Upvotes: 1

Related Questions