If your not using the unsafe keyword, I doubt you have a memory leak or a memory leak that you cam fix(i.e. It may be a problem with the database api).
Note: I wouldn't base memory leaks solely on the task manager's memory indicator since C#'s garage collector isn't consistent in its duties.
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
You shouldn't close and reopen the connection each time. You should check if it is open and if it isn't, open it. Also, database connections do use unmanaged resources (anything dealing with the system software does) and will need to have the Dispose() method called on it.
Momerath
Nearly a Senior Poster
3,384 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
Generally if the class has something to do with hardware (files on the drive, the screen, databases, etc.) it has an unmanaged component to it. The GC will not clean those up for you (the system will, eventually, after your program stops running). The easiest way to know is use intellisence. When you type your variables name and hit the . (<- thats a period over there, I know it's hard to see) you should get a pop-up box of all the methods available. If Dispose() is one of them, then you should Dispose of it.
One way to dispose of objects is the alternate use of the using statement. For example:
using (SqlCommand command = new SqlCommand("Select * from SomeTable") {
... rest of code here
}
This will automatically call Dispose() at the end of the statement block. It's the exact same as writing
SqlCommand command = new SqlCommand("Select * from SomeTable");
try {
... rest of code here
} finally {
if (command != null) {
command.Dispose();
}
}
The compiler just handles all the extra code for you. This is used commonly with files, since you tend to open them, read what you need, then close them. By using theusing syntax, you ensure that system resources are released.
Momerath
Nearly a Senior Poster
3,384 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558