简体   繁体   中英

How to dispose resources in third-party dll?

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.

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);
}

Calling GC.Collect() during runtime might solve the problem. Ref: https://docs.microsoft.com/en-us/dotnet/api/system.gc.collect?view=net-5.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM