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

How to prevent objects used by threads from being disposed? How to control the lifetime of the object?

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

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

ProcessText Class: 它读取给定输入目录中的文件,并在 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).然后,您需要控制需要多长时间才能引用新的可枚举对象,例如您可能必须在 ProcessAll() 方法的末尾使用 GC.KeepAlive(texts)