Using SQLSERVER 2008R2, VisualStudio 2010, .NET 4.0
I'm getting this periodic exception: "Server failed to resume the transaction - Desc 2000003" (number changes)
Reading online forums and here, I found the main cause is to properly instance and close the Connections.
What should my classes look like?
Create the DataContext on Class level and use it on all methods?
public class BusProcess
{
RENDBDataContext db = new RENDBDataContext();
public void Insert()
{
//Do stuff here...
db.InsertProcedure(...);
}
}
Create and dispose a new DataContext on each method through using() ?
public class BusProcess
{
public void Insert()
{
using(RENDBDataContext db = new RENDBDataContext())
{
//Do stuff here...
int sample = db.SomeObject.SingleOrDefault(...).Id;
db.InsertProcedure(...);
}
}
}
Or maybe a different approach (Best practice)
Generally speaking, the lifetime of a DataContext instance should be bound to a single unit of work -- which is exemplified by your second usage.
The first usage can also be fine, depending on how long-lived the enclosing class is -- but whatever the case there, ensure that class implements IDisposable, dispose of the enclosed DataContext in your implementation of Dispose(), and wrap usages of that class with using().
Second approach is better than having DataContext around all time. It will prevent memory consumption when calling Load etc. Also remember that connections are pooled, so creating new DataContext is not a big deal.
A combination of both. Use the first method but have your classes implement IDisposable and call dispose on the context in your classes dispose method. You then use your classes in using statements. You could also pass in a DataContext in a constructor of your class for added flexibility.
Related
I have some confusion in Linq to SQL.I am searching for an actual reason why Data context class gives follwing Exception some times .
"There is already an open data reader associated with this command which must be closed first
Specially in multitasking environment.Most people are saying that the reason is ,Data Context is not thread Safe.All are suggesting to use DataContex as one per unit of work.
Please refer following thread for best answer
Linq-to-SQL Data Context across multiple threads
But in my case,i am using another class call "A" which is implemented in Singleton pattern.Purpose of this class is ,provide Data context object in singleton manner.I am maintaining instance of this class "A" as global instance in derived class and calling to Datacontex by using particular instance.
My question is,
Will my method call cause uncontrolled memory growth ? based on my understanding,singleton maintaining one instance as static object .If my assumption is wrong ,please give me good explanation.
Note:
Any way my method call also throws same exception.So i am sure same problem is happen in this scenario also.
Your approach will cause problems in general. A DataContext is not intended to be a singleton. Just don't do it.
Even if A is a singleton, create a new DataContext within the appropriate methods within A, rather than having a DataContext as a variable within A. (You might also want to consider whether A should really be a singleton in the first place.)
I actually came here because I felt a singleton pattern would be perfect for the Linq Datacontext too. But after seeing your issues it makes since why it's not.
Here's an example of how I'd write a Singleton Linq DataContext:
class DataAccess
{
private static DataContext db = null;
private DataAccess()
{
}
public static DataContext GetInstance()
{
return db ?? (db = new DataContext());
}
}
In the singleton pattern you set the DataContext instance as static. Well, in a multi-threaded environment a static object is going to cause collisions like the errors you're seeing. You are lucky to get those errors. Using multiple threads you could submit changes from another thread and then have the original thread submit causing a big mess.
I'd stick to non static implementation. True me I know it's disappointing, I really wanted to use that pattern here too.
I have code similar to the following.
class MyController
{
[ThreadStatic] private DbInterface db;
public void ImportAllData()
{
using (db = new DbInterface())
{
var records = PullData();
PushData(records);
}
}
private DbRecord[] PullData()
{
return db.GetFromTableA();
}
private void PushData(DbRecord[] records)
{
db.InsertIntoTableB(records);
}
}
The alternative is a lot more cumbersome to maintain.
class MyController
{
public void ImportAllData()
{
using (var db = new DbInterface())
{
var records = PullData(db);
PushData(records, db);
}
}
private DbRecord[] PullData(DbInterface db)
{
return db.GetFromTableA();
}
private void PushData(DbRecord[] records, DbInterface db)
{
db.InsertIntoTableB(records);
}
}
As far as I can see, my first implementation:
is thread safe (assuming DbInterface is thread safe),
prevents any other process from touching the db variable, and
ensures db will always be disposed, even during an exception.
Is it bad practice to use the using statement on a variable with class scope? Have I missed something?
Personally, I prefer your second option.
The issue with the first design is that your effectively adding unnecessary coupling to the design. Your PullData and PushData methods cannot be used alone - they require that a call to ImportAllData or some other method that will setup and properly cleanup the db variable be called first.
The second option, while slightly more code (though not much), makes the intent very clear for each and every method. Each method knows that it needs to work on an external DbInterface instance passed into it. There is little or no chance of this being misused in the future.
Your first variant exposes db outside of the scope where it is managed by the using block. That opens the possibility of unintended side effects. For example, another method might use or even dispose of db. That could happen if you or a later maintainer forget the implicit contract for db or even through a typo in code.
I would not use the first variant.
Here is an alternative:
sealed class MyImporter
{
private readonly DbInterface db;
public MyImporter(DbInterface db)
{
this.db = db;
}
public void ImportAllData()
{
var records = PullData();
PushData(records);
}
private DbRecord[] PullData()
{
return db.GetFromTableA();
}
private void PushData(DbRecord[] records)
{
db.InsertIntoTableB(records);
}
}
In this case, holding onto the reference is a clear part of the class responsibility. It's also now pushing up the responsibility of disposal to the user. This more explicit construct reduces the temptation to add additional features to the 'Controller', which is how your first approach can go bad in the long run. Essentially we've refactored the Import function into a separate class so that the shared field access is no longer a problem.
That's what the construct is there for. I would be careful about putting a using into property, since convention dictates that property access is lightweight and the user does not necesarily want to trigger a create-dispose cycle when they think they're just accessing a variable.
However the comments below about the structure of the code are important - if you want to do the import once, it becomes a setup step that users need to know about. If you can envision different access patterns the dependency injection setup allows the user to control the creation and disposal of the connections.
I have a site which uses a C# class file, and at the top of the file, I have:
JTSEntities database = new JTSEntities(); (an ADO.NET thingy).
I have it right up the top because I don't really feel like writing the same thing over and over again.
But it raises one question... Because it's up the top there, how will it get disposed, and when - and how can I dispose of it (or do I need to) when the user closes the page?
It is bad practice to hold on to anything that wraps a database connection for longer than needed.
The best practice would be to release the database connection as soon as it is no longer needed for the current operation (such as populating initial values, etc.), e.g. something like
using (JTSEntities database = new JTSEntities())
{
// Use database
}
if it implements IDisposable.
If for some reason you must keep it alive for the duration of the page, be sure you call an appropriate method to release resources (.Close(), .Dispose(), etc.) in the page close event handler.
Ok so, based on the type of the attribute, we can say that it's an instance attribute. This means that this attribute will have the same lifecyle as the object that has it, unless its instance is passed to another object.
If it's protected, then only the owner object and its childs (that is, objects that inherit from this class) will have access to it. If you don't pass it as a reference argument, then we're ok with the first statement: it will be cleaned by the GC as soon as the object is cleaned.
If you just use this object on a regular webform page lifecycle, then you don't have to worry with disposing it. The page lifecycle will do it for you.
Regards
Implement IDisposable in this class and dispose of this object inside the Dispose() method. When using this class, make sure you call Dispose when you are done (preferably with a using block)
Beyond that, you don't need to worry about it.
public class MyClass : IDisposable
{
protected JTSEntities database = new JTSEntities();
public void Dispose()
{
database.Dispose();
}
}
// When calling this class
using(MyClass cls = new MyClass())
{
// Do Stuff
} // Dispose is automatically called here.
I am using .NET 3.5 C#. I have a simple connection class with only two methods: OpenConnection() and CloseConnection(). I defined this class as Static so that I don't have to create an instance while calling methods. I want to know whether:
(1) I should create an interface with method definitions for OpenConnection and CloseConnection and thereby use this Interface with Connection class. There is no reason to use an interface but I was thinking whether the Connection can be made more professional.
(2) Is it fine to declare this class as Static?
There are two entirely different approaches
Singleton: Single object across the application.
In this case, you will have to take care of the locking mechanism as well.
class Connection
{
public static Connection Instance() {
if (_instance == null) {
lock (typeof(Connection)) {
if (_instance == null) {
_instance = new Connection();
}
}
}
return _instance;
}
protected Connection() {}
private static volatile Connection _instance = null;
}
Implement IDisposable:
Alternatively, you can implement IDisposable in your Connection class, and let it disposed automatically using the using keyword. For instance:
using(Connection c = new Connection(SomeConfiguration)) //Opens the connection.
{
Something(c);
}// Closes the connection. Dispose is implicitly called in the scope of the using statement.
Or if you want Generic Connection class, then Marc has responded with an excellent database connection class example here.
Regarding point 1; you can use interface; iff:
You want loose coupling, componentization, and maintainability in your code.
You want to provide guarantee that the classes shall behave exactly as methods/contracts defined in interface. For instance, in this case, if you extend your class from IDisposable, the interface imposes that not only objects can be disposed without getting compiler errors, but that they should be disposed. So, similar guarantees can be provided in your code by simply adhering to an interface.
You have a team that is going to working on a large module; and you want to keep code consistent; so you can define an interface and add some restrictions, that would help integrate the it easily. For instance:
You know you have a module that is going to handle alot of connections, different types of connections - some of which may be identified later during the development. But what you know for sure is that all types of connection shall be able to Open and Close; and you also want all of the developers to stick to this rule. So you can come up with an interface like:
interface IMyConnection
{
Open();//Opens the connection
Close();//Closes the connection
}
You expect have certain classes that does a lot of complex work and won't be finished before the rest of the project; then rest of the project can use the interface and avoid being dependent on that class.
You plan to deploy your product commercially; and want it to be extendable by 3rd party developers.
If you use interface, you cannot define Static method. (or in other word, static method is always pointing to the class defined, so the interface cannot provide abstraction at this point).
A class can be static, as long as you want everything shared, and extension to it is not necessary. But I would strongly recommend you to look at Singleton Pattern and Abstract Factory as alternative to your design problem.
interface IConnection {
void Connect();
void DisConnect();
}
class TCPCustomConnection : IConnection{
// implement other stuff
// Singleton Pattern
static IConnection Instance {
privateInstance = privateInstance ?? new TCPCustomConnection();
return privateInstance;
}
}
From what you said so far, I don't see how the interface adds value. If it does not add value, it should be eliminated from the design. The interface introduces two new problem: You need to get a pointer to the interface implementation, and usually you want to avoid asking for it repeatedly. So don't do it unless adds value (in a tangible, not metaphysical way) to your design.
An interface might add value if it simplifies unit testing of your code, or if it is important to remove the runtime dependency on the assembly that implements the connection. This is very fashionable these days.
simple a static class is requird, if it just used for demarcating operations like open and close connection, favor simplicity rather, dont code for future scenario until it is absolutely necessary and don't change existing working code till you reach a point where it is absolutely requirea
My advice:
(1) Why you need to write your own Connection class since it's "a simple connection"? None of the built-in classes meets your requirement?
(2) According to MS examples, it's really weird to make Open and Close methods static. We are used to this:
conn.Open();
conn.Close();
instead of:
MyConnection.Open(conn);
MyConnection.Close(conn);
(3) Using interfaces is a good idea, especially IDisposable:
class MyConnection : IDisposable
{
public void Dispose()
{
//close the connection and release resources
}
}
using (MyConnection conn = new MyConnection(connStr))
{
} //automatically Dispose()
If you have different connection type, like UDP, TCP, COM Port, ... using interface is good for manageability, but in the case which you have just one connection there is no need to use interface, also i think using static and singleton is not useful here, you should have a service for your tcp connection to always keep it up, and when you got disconnected you should be able to repair connection. for a good tcp server sample see http://fadd.codeplex.com/SourceControl/changeset/view/58859#1054893.
Even if you think that you'll only ever need one connection, I'd still use an instance class that implements an interface to handle it.
Why?
I can easily swap implementations if I need to (or refactor an existing one).
I can unit test things that depend on the class by mocking the connection.
I can more easily control the lifecycle of the connection (eg by using IDisposable).
Consumers of any API I write can see what my dependencies are.
If the single instance requirement does change, I don't have to unpick all the references to the static/singleton methods.
The testing point here is important: if you use a static reference to a fixed external resource, your code will be virtually impossible to unit test independently of that resource.
See this answer for a similar discussion about static versus instance classes and methods.
I've been googling a ton on repository patterns with Linq over the last few days. There's a lot of info out there but it's often contradictory and I'm still looking for a definitive source.
One of the things I'm still not sure about is whether the repository should instantiate it's own DataContext and have a SubmitChanges method, or if the DataContext should be injected and the submission handled externally. I've seen both designs but no real comment on the reasoning.
Anyway, the following pattern is pretty common
class Repository<T>
{
DataContext db = new LinqDataContext();
public IEnumerable<T> GetAll() { ... }
public T GetById() { ... }
... etc
public void SubmitChanges() { ... }
}
So my main question is, with the above implementation, why does the repository not need to implement IDisposable? I've seen literally hundreds of examples as above, and none of them seem to bother disposing the DataContext. Isn't this a memory leak?
Disposing a DataContext closes the underlying connection if you have autoclose set to false. If you do not call dispose, you have to wait for the GC to call it for you. You should implement IDisposable and dispose of your repositories which should in turn dispose their DataContext.
Another solution is to create a new data context for each method in your repository if your methods don't work together within a single transaction. Then you can dispose your contexts as soon as they are used via a using() directive.
Not necessary but you probably should implement IDisposable.