title: Worker thread termination in MFC
body: <p>What is the correct way to terminate a worker thread if it is taking too long to complete? I've read several articles claming that TerminateThread should be used with extreme caution, but I can't find any viable alternative.</p>
  
  <p>Psudo code:</p>
  
  <pre><code>void CMyDialog::RunThread()
  {
      CWinThread* pThread;            // pointer to thread
      DWORD dwWaitResult;             // result of waiting for thread
  
  
      // start thread
      pThread = AfxBeginThread(beginThread, this, 
                             THREAD_PRIORITY_NORMAL, 
                             0,     
                             CREATE_SUSPENDED);
      pThread-&gt;m_bAutoDelete = FALSE;
      pThread-&gt;ResumeThread();
  
      // wait for thread to return
      dwWaitResult = ::WaitForSingleObject(pThread-&gt;m_hThread, (30 * 1000)); 
  
      switch (dwWaitResult) 
      {
          case WAIT_OBJECT_0: 
  
              delete pThread;
  
              // success, continue
  
              break;
  
          case WAIT_TIMEOUT: 
  
              // thread taking too long, terminate it
              TerminateThread(pThread-&gt;m_hThread, 0);
              delete pThread;
  
              break;
  
      } // end switch on wait result
  
  
  } 
  
  
  UINT CMyDialog::beginThread(LPVOID pParam)
  {
      // convert parameter back to dialog object and call method
      CMyDialog* dlg = (CMyDialog*) pParam;
      dlg-&gt;readDuration();
  
      return 0;
  } // end beginThread
  
  
  void CMyDialog::readDuration()
  {
      // call a dll function that may take longer than we are prepared to wait, 
      // or even hang
  
  } // end readDuration
  </code></pre>
  
  <p>Is this acceptable? All comments and suggestions gratefully recieved.</p>
  
  <p>I am using MFC/C++ in Visual Studio 2008. Developing on Vista, targeting XP, Vista and 7.</p>