Reputation: 69
I have a console application that needs to create multiple objects of type <T>
and T
is inside another dll that I don’t own.
When an object of type T
is created, it loads a XML in memory, but it never releases it.
So if you create too many objects of type T
, an OutOfMemoryException is thrown.
The dll doesn't provide a dispose method for that Object and I can’t interact with the XML directly.
Is there a way to dispose of objects of a certain type that were created by a dll that I don’t own ?
I'm using .NET 4.6
The third-party dll is the dll of Trados Studio, for the people who know the program.
Upvotes: 4
Views: 1867
Reputation: 21
Calling GC.Collect() during runtime might solve the problem. Ref: https://learn.microsoft.com/en-us/dotnet/api/system.gc.collect?view=net-5.0
Upvotes: 0
Reputation: 10055
Just set the instance of the 3rd part object to null and create a new instance. The garbage collector will eventually clean up the object that you set to null and you wont get an out of memory exception anymore.
public class Class1
{
private StringBuilder sb = new StringBuilder();
public void loadFile()
{
using(StreamReader sr = new StreamReader("C:\\test.txt")) // Loads large text file.
{
sb.Append(sr.ReadToEnd());
}
}
}
static void Main()
{
fileloader.Class1 inst = new fileloader.Class1(); // Assume this is the instance of your 3rd party object.
do
{
if(inst == null)
{
inst = new fileloader.Class1();
}
for (int i = 0; i < 100; i++)
{
inst.loadFile();
}
inst = null; // allows the object to be GC'ed. Without this i get the OutOfMemoryException
Thread.Sleep(1000);
} while (true);
}
Upvotes: 1