创建线程会在终止时挂起MFC对话框应用程序

时间:2010-07-19 03:51:28

标签: visual-c++ mfc multithreading hang

我已经缩小了一个问题。

  1. 我创建了一个简单的Dialog应用程序 VC ++ 6.0。
  2. 我在主要之前开始一个帖子 对话框DoModal()被称为
  3. 我退出应用程序 - 有时候 应用程序立即关闭, 其他时间它会挂起10秒钟
  4. 是什么原因引起的?我试过_beginthread(),_ beginthreadex()和AfxBeginThread()。他们都做同样的事情。

    如果我在DoModal()调用之后添加Sleep(50)(当GUI完成处理时),程序似乎每次都没有问题地终止。

    是什么原因导致我缩小这个问题的原因是我有一个Win32 DLL做同样的事情。我的DLL有一个线程,我注意到我的应用程序使用这个DLL有时需要一段时间才能停止。消除DLL并创建最简单的程序导致了同样的事情 - 这就是我上面所描述的。

    以下是我添加到沼泽标准MFC Dialog应用程序的代码:

    UINT Thread( void * )
    {
      for( ;; )
      {
        Sleep( 50 );
      }
    
      AfxEndThread( 0 );
      return 0;
    }
    
    /////////////////////////////////////////////////////////////////////////////
    // CThreadTest2App initialization
    
    BOOL CThreadTest2App::InitInstance()
    {
        AfxEnableControlContainer();
    
        // Standard initialization
        // If you are not using these features and wish to reduce the size
        //  of your final executable, you should remove from the following
        //  the specific initialization routines you do not need.
    
    #ifdef _AFXDLL
        Enable3dControls();         // Call this when using MFC in a shared DLL
    #else
        Enable3dControlsStatic();   // Call this when linking to MFC statically
    #endif
    
      AfxBeginThread( Thread, 0 );
    
        CThreadTest2Dlg dlg;
        m_pMainWnd = &dlg;
        int nResponse = dlg.DoModal();
    
      //Sleep( 50 );   // Works when I add this ?????
    
        if (nResponse == IDOK)
        {
        }
        else if (nResponse == IDCANCEL)
        {
        }
    
        // Since the dialog has been closed, return FALSE so that we exit the
        //  application, rather than start the application's message pump.
        return FALSE;
    }
    

    有人可以帮我正确关闭我的应用程序吗?我最终要做的是提供一种方法让我的DLL关闭,而不会被明确告知通过调用应用程序停止thead。

    由于 保罗

1 个答案:

答案 0 :(得分:0)

嗯,你的线程函数中有无限循环,永远不会接到AfxEndThread的调用!

如果你想从外面停止线程,你必须在其中编码一个信号机制,如果你不得不停下来检查循环内部。