I keep getting this error: "Invalid attempt to cause" Read "when the reader is closed"

Here is my code, I close and open the reader, and it still does not work. Several threads can access this function at the same time, but there is a lock. It works several times in the beginning, but sooner or later I get the exception "Invalid attempt to cause Reading when the reader is closed" in

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?

0
source share
1 answer

Try improving the code a bit:

 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 completely reentrant and thread safe. You do not need a lock.

+11
source

All Articles