Reputation: 1504
Here is my code, I close and open the reader and it's still not working. A few threads can access this function concurrently but there is a lock. It works a few times in the beginning but sooner or later I get the exception 'Invalid attempt to call Read when reader is closed' at
private IList<BursaUser> GetUsers(SqlCommand cmd)
{
IList<User> users = new List<User>();
User user;
lock (thisLock)
{
SqlDataReader dr = null;
try
{
Conn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
user = new User
{
UserId = Convert.ToInt32(dr["WorkerNum"]),
CompanyName = dr["CompanyName"].ToString(),
WorkerName = dr["WorkerFirstName"] + " " + dr["WorkerFamilyName"],
Phone = dr["Phone"].ToString()
};
if (dr["QueueNum"] != null && dr["QueueNum"] != DBNull.Value)
{
user.Queue = new Queue
{
HasAlreadyEntered =
dr["flgAppear"] != null && dr["flgAppear"].ToString() == "Y",
IsFromWebsite = dr["TookFrom"].ToString() == "1",
IsMelutash = dr["IsMelutash"].ToString() == "1",
TimeOrdered = DateTime.Parse(dr["DateTime1"].ToString()),
QueueNum = Convert.ToInt32(dr["QueueNum"]),
SMS = dr["SMSCode"].ToString()
};
}
users.Add(user);
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (dr != null)
{
dr.Close();
dr.Dispose();
}
}
return users;
}
}
What gives?
Upvotes: 0
Views: 3423
Reputation: 1039248
Let's try to improve this code a little:
private IEnumerable<BursaUser> GetUsers()
{
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT WorkerNum, CompanyName, ... FROM Users";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var user = new User
{
UserId = reader.GetInt32(reader.GetOrdinal("WorkerNum")),
CompanyName = reader.GetString(reader.GetOrdinal("CompanyName")),
// TODO: complete other fields
};
// TODO: do the tests and complete the complex properties
yield return user;
}
}
}
}
Now this code is perfectly reentrant and thread safe. You don't need any locking.
Upvotes: 11