开发者

c get the return value of thread function & UI thread stucked

I wanted to use a thread to do something that could not return immediately when i click a button called button1 here is my code :

LRESULT CALLBACK DlgProc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    switch(Msg)
    {
    case WM_INITDIALOG:
        //do something.......

    case WM_COMMAND:
        switch(LOWORD(wParam))
        {
        case IDC_BUTTON1:
            {
                HANDLE thread1;
                DWORD exitCode;
                DWORD thread1ID;
                thread1 =  CreateThread(NULL,0,threadProc,(LPVOID)2,0,&thread1ID );
                WaitForSingleObject(thread1,INFINITE);
                GetExitCodeThread(thread1,&exitCode);

            }
            return TRUE;

        }
        return TRUE;
    //other code..................
    }
    //return DefWindowProc (hWndDlg, Msg, wParam, lParam) ;
    return FALSE;
}

thread1 prototype:

DWORD WINAPI thread1(LPVOID n)
{
    Sleep((DWORD)n*1000*2);
    return (DWORD)n * 10;
}

After I click button1 (ID:IDC_BUTTON1),UI thread was stucked for about the amount of how long Sleep did. if I don't use WaitForSingleObject , exitCode always return 259(STILL_ALIVE)?

How can I do to get the return value of thread1 and UI thread couldn't be stucked ?

EDIT

using PostThreadMessage :

case IDC_BUTTON1:
    {
        HANDLE thread1;
        DWORD exitCode;
        DWORD thread1ID;
        DWORD mainThreadId = GetCurrentThreadId();
        thread1 =  CreateThread(NULL,0,threadProc,(LPVOID)mainThreadId,0,&thread1ID );

    }
    return TRUE;

and a new Messag开发者_如何学Pythone in DlgProc:

case WM_FINISHED_FETCH:
    MessageBox(NULL,NULL,NULL,MB_OK);
    return TRUE;

mainThreadId is the ui thread id.

in threadProc

PostThreadMessage((DWORD)mainThreadId,WM_FINISHED_FETCH,0,0);

code under WM_FINISHED_FETCH never trigger.


Whats the point in creating a thread if you are going to block the ui thread to wait for it? If you need to do something on the ui thread once your other thread finishes, consider posting a private message to the ui thread. See PostThreadMessage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜