c# - 如何防止线程使用的对象被释放?如何控制对象的生命周期?

标签 c# c++ multithreading memory-leaks com

假设我们有 C# 和 C++ 通过 COM 进行通信。 在 C++ 中,我们有两个名为 ProcessTextText 的类。

文本类: 保存文本详细信息对象,如字符串、numberOfPages 等

ProcessText 类: 它读取给定输入目录中的文件,并在 2 个函数的帮助下使用 C# 组件处理文件

ReadAll() 方法: 它读取目录中的所有文件创建 Text 对象并将其传递给 ProcessAll()。

ProcessAll() 方法: 考虑多线程场景,其中 C# 组件的输入文本对象被馈送到线程。

在 ProcessAll() 中,Text 对象的范围已经完成,我需要一些机制来防止对象超出范围,直到线程完成处理,如果这不可能,至少触发 C# 组件停止处理文本对象。

What I specifically wants can it be achieved by using Destructor of C++ class? If during destruction of Text Object we query C# component about the status of the Text object and can we block its memory from destruction without waiting on the thread to complete operation? Also if the object is not destroyed but still the memory will be freed. Can we prevent the memory from getting freed? If memory still holds value as memory leak can it be used by threads safely and also can it be taken up the OS to write some other things? If it can be taken up by the OS can we block this memory by using pointer and size of the object?

最佳答案

一般来说,您在 C# 中所要做的就是 GC.KeepAlive(text)在线程的末尾。

如果这还不够(例如,因为您需要让这些 Text 对象保持事件状态,直到所有线程完成其工作),那么您必须保留对 Text 的引用对象。也许实现这一目标的最简单方法是使用 PLINQ,例如files.AsParallel().Select(...).ToList() (或 SelectMany(...) )。

这样,在并行枚举结束时,您将拥有对所有 Text 的引用。对象,假设这是您将从 Select 返回的内容(或 SelectMany )。然后,您需要控制需要多长时间才能引用新的可枚举对象,例如你可能必须使用 GC.KeepAlive(texts)ProcessAll() 的末尾方法。

关于c# - 如何防止线程使用的对象被释放?如何控制对象的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29147302/

相关文章:

java - 线程 "main"java.util.NoSuchElementException 中出现异常帮助迷宫游戏

c++ - C++生产者使用者陷入僵局

java - 在JMS/ActiveMQ中如何使用同步来保持MessageConsumer的存活?

c# - 名为 'DefaultApi' 的路由已经在路由集合中

c# - 从 .net(C#) 中的 Webbrowser 控件检索选定的文本

c++ - 在 C++ 中使用 libcurl 将图像上传到 Parse 服务器

c++ - 数组的 Stackoverflow 数组

c# - 重构 LINQ 方法

c# - 如何在 C# 中将 Excel.Range.Interior.Color 转换为 System.Drawing.Color?

c++ - 单例导致链接器错误 : "already defined"