I tried to call this method from multiple threads trying to get the ID from the same string. I am always getting this exception at the line where I create the SqlDataReader:
There is already an open DataReader associated with this Command which must be closed first.
I don't know where the problem is. I am using a lock() statement so I use the command only once, then I dispose it. Kinda new to database programming so I don't know where my error is.
Thanks!
public int UsernameGetID(string username)
{
using (var command = new SqlCommand("SELECT user_id FROM " + ServerConstants.Database.TableUserInformation + " WHERE username = @Username", connection))
{
lock (command)
{
SqlParameter param = new SqlParameter("@Username", SqlDbType.VarChar, username.Length);
param.Value = username;
command.Parameters.Add(param);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return (int)reader[0];
}
else
{
// username doesn't exists
return 0;
}
}
}
}
}
connectionvariable, but create the connection in theUsernameGetIDmethod itself?connectionfor other readers? If yes, you can try to addMultipleActiveResultSets=true;to the end of the connection string. Or just create a newSqlConnection