Tuesday, March 5, 2013

Setting FILETIME Timeout for SetThreadpoolWait

Using Window's new (since Vista) Threadpool is great.  You can read up on it here.  If you want some sample code on usage patterns, message me, and I can do a post on it later.

The threadpool has a generic wait on an handle (eg. event, process, etc.) mechanism.  It even has a timeout so say you want to wait either for an event or a timeout, but the timeout is in FILETIME format.  How do you convert a specified amount say in ms of time into a FILETIME?


HRESULT DoWaitWithTimeout(
    __in DWORD Timeout) // in ms
{
    HRESULT hr = S_OK;
    PMY_CONTEXT pContext = NULL;
    FILETIME timeout = {0};

    pContext = (PMY_CONTEXT)my_alloc(sizeof(MY_CONTEXT));

    if (!pContext) {
        hr = E_OUTOFMEMORY;
        goto Exit;
    }

    ZeroMemory(pContext, sizeof(MY_CONTEXT));
    pContext->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (!pContext->hEvent) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto Exit;
    }

    pContext->hWait = CreateThreadpoolWait(
            MyWaitCallback,
            pContext,
            NULL);

    if (!pContext->hWait) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto Exit;
    }

    if (Timeout) {
        ULARGE_INTEGER ulTimeout = {0};

        // Timeout in ms, FILETIME is in 100 ns increments
        ulTimeout.QuadPart = Timeout * -10000; 
        timeout.dwHighDateTime = ulTimeout.HighPart;
        timeout.dwLowDateTime = ulTimeout.LowPart;
    }
  
    SetThreadpoolWait(
            pContext->hWait,
            pContext->hEvent,
            &timeout);
// ...



No comments:

Post a Comment