混合模式 C++/CLI 应用程序未正确关闭 CLR [英] Mixed-mode C++/CLI app not shutting down CLR correctly

查看:35
本文介绍了混合模式 C++/CLI 应用程序未正确关闭 CLR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的混合模式 MFC 应用程序正在创建错误的内存泄漏,因为在 MFC dll 关闭之前 CRT 没有时间关闭.

My mixed-mode MFC application is creating false memory leaks because the CRT doesn't have time to shut down before the MFC dll is shut down.

我有一个非常简单的小应用程序可以显示问题:

I have a very simple little app that shows the problem:

#include <windows.h>
#include <iostream>

struct LongTimeToDestroy
{
  ~LongTimeToDestroy()
  {
    std::cout << "Will get called!" << std::endl;
    Sleep(3000);
    std::cout << "Won't get called!" << std::endl;
  }
};

LongTimeToDestroy gJamsUpTheCRT;

int main()
{
}

使用 cl.exe/clr test.cpp 编译.运行时,您会得到:

Compile with cl.exe /clr test.cpp. When run, you get:

Will get called!

问题的症结在于:在 gJamsUpTheCRT 之前声明的任何静态/全局变量都不会被释放.例如,在我的例子中,MFC CWinApp 派生类没有被清理.

The crux of the problem is: any static/global variables that were declared before gJamsUpTheCRT will not be deallocated. For example, in my case the MFC CWinApp-derived class is not cleaned up.

这是预期的行为吗?我想让我的应用完全关闭.

Is this expected behaviour? I would like to allow my app to completely shut down.

谢谢,

推荐答案

这是预期的行为吗?

Is this expected behaviour?

是的,尽管您必须阅读 CLI 规范中的细则.它承诺在程序终止时调用托管对象的终结器.但需要注意的是,执行此操作的终结器线程需要两秒钟才能完成工作.如果需要更长的时间,则 CLR 会假定存在严重错误.就像在不会收到信号的同步对象上阻塞代码的常见诅咒一样.它通过中止终结器线程并允许程序终止来处理它.没有诊断.

Yes, although you have to read the fine print in the CLI spec. Which promises that finalizers on managed objects are called when the program terminates. But with the caveat that the finalizer thread that does this gets two seconds to get the job done. If it takes longer then the CLR assumes that there's something drastically wrong. Like the common curse of having code blocking on a synchronization object that isn't going to get signaled. Which it deals with by aborting the finalizer thread and allowing the program to terminate. No diagnostic.

你必须解决这个限制.

这篇关于混合模式 C++/CLI 应用程序未正确关闭 CLR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆