Monday, August 19, 2013

How to stop a blocking thread from another function that start in other in MFC

ISSUE: In server client scenario it is mandatory to use thread where sever is listening on a particular port.
Now in click of stop button ,how to stop this running thread.


SOLUTION:

#include <Windows.h>

HANDLE m_Thread_handle;
CWinThread *cTh;
static UINT __cdecl StaticThreadFunc(LPVOID pParam);
UINT ThreadFunc();
Step 1. Declared these on header file.

Step 2. Starting the thread from a function or button click ---


void CServerDlg::OnBnClickedStart()
{
    // TODO: Add your control notification handler code here

    cTh = AfxBeginThread(
    StaticThreadFunc,
    this);
    m_Thread_handle = cTh->m_hThread;
}
Step 3. Thread initialization function --

 UINT __cdecl CServerDlg::StaticThreadFunc(LPVOID pParam)
{
    CServerDlg *pYourClass = reinterpret_cast<CServerDlg*>(pParam);
    UINT retCode = pYourClass->ThreadFunc();

    return retCode;
}
Step 4. Work processing function for thread --

UINT CServerDlg::ThreadFunc()
{
    // Do your thing, this thread now has access to all the classes member variables
    CString txtname;
    GetDlgItemText(IDC_EDIT1, txtname);
    int iPort = _wtoi( txtname.GetString() );
    m_pServer = new ServerManager(this);
    m_pServer->StartListening(iPort);
             // while loop on start listening that are blocking call
    return 0;
}
Step 5. Now to close the thread from clicking stop button ---

void CServerDlg::OnBnClickedStop()
{
    // TODO: Add your control notification handler code here
    CloseHandle(m_Thread_handle);
    delete m_pServer;
}

No comments:

Post a Comment

How to enable hotspot in TPG iPhone

 By default, the hotspot does not work on the phone. It will ask you to contact the provider. This video will help you bypass the network ...