المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Design Question for DataReader error



C# Programming
02-22-2010, 03:40 AM
Ok, let me start off by saying that this is my first post ever, so be gentle.

I am having an issue with a web service where I am randomly getting the following error:

System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
The error stems from the same object all of the time. So after investigating the issue I believe it is happening because I am using a static TableAdapter for one particular sql server database table. This is a surrogates table which is used to track keys to all of the other tables within the database (Not my design and I cannot change it). http://www.barakasoft.com/script/Forums/Images/smiley_cry.gif

Here is my question:
Would it be better to implement the static TableAdapter and lock that or to create a generic object to lock and create a new TableAdapter every time I would like a new key. This Surrogate table has roughly 30 different tables that it manages keys for and it probably will create between 100 and 200 keys per call. So creating a TableAdapter every time that method is called seems like wasted resources but I am not sure if having a static TableAdapter is the best way to go either. Also, any better way to handle it would be greatly appreciated.

Example Code:
This Way
public class SurrogateClass
{
public SurrogateClass(){}

private static SurrogateTableAdapter SurrogateAdapter = new SurrogateTableAdapter();

public static int GetSurrogateByTableName(String tableName)
{
int result = 0;
lock (SurrogateAdapter)
{
SurrogateRow row = SurrogateAdapter.GetSurrogateByTableName(tableName).FindByTABLENAME(tableName);
if (row != null)
{
int.TryParse(row.SURROGATE.ToString(), out result);
result += 1;
row.SURROGATE = result;
SurrogateAdapter.Update(row);
}
else {
result = -1;
}
}
return result;
}
}

Or this way
public class SurrogateClass
{
public SurrogateClass(){}

private static object lockerOjbect = new object;

public static int GetSurrogateByTableName(String tableName)
{
int result = 0;
lock (lockerObject)
{
using (SurrogateTableAdapter SurrogateAdapter = new SurrogateTableAdapter())
{
SurrogateRow row = SurrogateAdapter.GetSurrogateByTableName(tableName).FindByTABLENAME(tableName);
if (row != null)
{
int.TryParse(row.SURROGATE.ToString(), out result);
result += 1;
row.SURROGATE = result;
SurrogateAdapter.Update(row);
}
else {
result = -1;
}
}
}
return result;
}
}