gpt4 book ai didi

c# - 如何配置第三方dll中的资源?

转载 作者:行者123 更新时间:2023-11-30 17:38:18 27 4
gpt4 key购买 nike

我有一个控制台应用程序需要创建多个 <T> 类型的对象和 T在我不拥有的另一个 dll 中。

当对象类型为 T创建后,它会在内存中加载一个 XML,但它永远不会释放它。因此,如果您创建了太多 T 类型的对象, 抛出 OutOfMemoryException。dll 没有为该对象提供处置方法,我无法直接与 XML 交互。

Is there a way to dispose of objects of a certain type that were created by a dll that I don’t own ?

我正在使用 .NET 4.6

第三方dll是Trados Studio的dll,供懂程序的人使用。

最佳答案

只需将第 3 部分对象的实例设置为 null 并创建一个新实例。垃圾收集器最终会清理您设置为 null 的对象,并且您不会再遇到内存不足异常。

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

关于c# - 如何配置第三方dll中的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36891260/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com