开发者

C++ threading to download

I need help with C++ threading stuff, I have created a dll which has a exported function as downloadfile (to download a file from the internet). This function in turns create a thread to download a file (the function used to download a file is blocking function i.e. URLDownloadToFile that's why I put the download functionality on thread).

I want to achieve following.

  1. my call to downloadfile function should not block the main thread.

  2. I want 开发者_StackOverflow社区to download more than one file at a time.

remember that, download functionality is in the dll created in C++ and this dll will be used in Pascal.

following is the code snippet:

struct DOWNLOADPARAM
{
    HANDLE hEventStop;
    TCHAR *szURL;
    TCHAR *szFilePath;
};


DWORD WINAPI Transfer(void *hw)
{
    Mutex mutex_;

    DOWNLOADPARAM *const pDownloadParam = static_cast<DOWNLOADPARAM *>(hw);
    CBSCallbackImpl bsc(NULL, pDownloadParam->hEventStop);


           const HRESULT hr = ::URLDownloadToFile(NULL,pDownloadParam->szURL  ,pDownloadParam->szFilePath,0,&bsc);


    return 0;
}


extern "C" void  __declspec(dllexport)   downloadfile(TCHAR *url, TCHAR *dest)
{
    Mutex mutex_;

    DWORD dwThreadId;
    DOWNLOADPARAM *obj = new DOWNLOADPARAM();
    obj->szURL      = url;
    obj->szFilePath = dest;


    if((hThread = CreateThread(NULL, 0, Transfer, (LPVOID)obj, 0,&dwThreadId)) != NULL)
    {
    }


// Following code block the thread untill finished 

    WaitForSingleObject(hThread, INFINITE);
        TerminateThread(hThread, 0);
    CloseHandle(hThread);
}


It looks like your downloadFile function is waiting for the download thread to finish before it returns, which will cause it to block just like the URLDownloadToFile function does. I would suggest that you break this apart into two operations; downloadFile should return some sort of handle or event that the calling program can use to determine whether the operation has completed, and then when it has, provide a second function that cleans up the thread and handles. That way, the calling program can continue to run and use a WaitForMultipleObjects or some other mechanism to allow it to perform its own processing while still being notified when the download has completed. My Win32 is sketchy at best, so I can't really draft up some example code, but I hope the design idea is helpful.


Calling WaitForSingleObject on thread handle immediately after launching the thread is nothing more than a synchronous/blocking call. You should defer WaitForSingleObject.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜