I am developing a utility class that contains static methods that will be frequently called by multiple threads. I am noticing that memory use is growing over time, so it seems to me that I have some memory leaks.
Here is a simple example of the pattern I am using for these static methods:
public static int CreateNewThing(int IDofSomeDBObjectHoldingInfoToCreateNewThing)
{
using(SomeDBContext context = new SomeDBContext(connectionString))
{
SomeDBObjectHoldingInfoToCreateNewThing createNewThingyInfo = context.SomeDBObjectsHoldingInfoToCreateNewThing.First(obj => obj.ID == IDofSomeDBObjectHoldingInfoToCreateNewThing);
// Do some stuff to create the new object
// Return the ID of the newly created thingy...
return theNewThingThatWasCreated.ID;
}
}
My question is whether using ‘using’ statements or directly calling Dispose inside static methods actually clears up any memory. Granted, I haven’t stated the overall architecture or purpose of this application, but I am also wondering if I’m using the best pattern here. What are the best practices for creating thread-safe utility classes in .NET?
Not necessarily – you’d need to give more data for us to really have a good idea about that.
usingstatements aren’t about cleaning up memory. That’s the GC’s job. They’re about releasing non-memory resources. Whether you’re in a static method or not is completely irrelevant to whether theSomeDBContextought to be disposed or not.