다음을 통해 공유


IHttpServer::AssociateWithThreadPool 메서드

비동기 완료 작업을 스레드 풀과 연결합니다.

구문

virtual HRESULT AssociateWithThreadPool(  
   IN HANDLE hHandle,  
   IN LPOVERLAPPED_COMPLETION_ROUTINE completionRoutine  
) = 0;  

매개 변수

hHandle
[IN] HANDLE 비동기 작업에 대한 입니다.

completionRoutine
[IN] LPOVERLAPPED_COMPLETION_ROUTINE 함수 포인터입니다.

반환 값

HRESULT입니다. 가능한 값에는 다음 표에 있는 값이 포함되지만, 이에 국한되는 것은 아닙니다.

설명
S_OK 작업이 성공했음을 나타냅니다.

설명

개발자는 메서드를 AssociateWithThreadPool 사용하여 비동기 입력/출력 작업에 대한 핸들을 IIS 스레드 풀과 연결할 수 있습니다. 해당 핸들과 연결된 비동기 작업은 IIS 스레드 풀 내에서 완료되므로 메서드를 사용하면 자체 스레드 풀 AssociateWithThreadPool 을 유지 관리하지 않고도 일련의 비동기 작업을 수행할 수 있습니다.

예제

다음 코드 예제에서는 메서드를 사용하여 AssociateWithThreadPool 비동기 입력/출력 작업이 필요한 조건을 만들고 비동기 완료 루틴을 IIS 스레드 풀과 연결하는 HTTP 모듈을 만드는 방법을 보여 줍니다.

#define _WINSOCKAPI_
#include <windows.h>
#include <sal.h>
#include <httpserv.h>

// Create a pointer for the global server interface.
IHttpServer * g_pGlobalInfo = NULL;

// Create a global file handle.
HANDLE g_hFile = NULL;

// Create a utility method for asynchronous completion.
VOID
__stdcall
MyCompletionRoutine(
    DWORD dwErrorCode,
    DWORD dwNumberOfBytesTransfered,
    LPOVERLAPPED lpOverlapped)
{
    if ((g_hFile != NULL) && (g_hFile != INVALID_HANDLE_VALUE))
    {
        CloseHandle(g_hFile);
    }    
    return;
}

// Create the module class.
class MyHttpModule : public CHttpModule
{

public:
    REQUEST_NOTIFICATION_STATUS
    OnSendResponse(
        IN IHttpContext * pHttpContext,
        IN ISendResponseProvider * pProvider
    )
    {
        UNREFERENCED_PARAMETER( pHttpContext );
        UNREFERENCED_PARAMETER( pProvider );

        BOOL fAuthenticated = FALSE;

        // Retrieve an IHttpUser interface.
        IHttpUser * pHttpUser = pHttpContext->GetUser();
        char * pszUserName = NULL;
        PCWSTR pwszUserName = NULL;

        // Test for an error.
        if (pHttpUser != NULL)
        {
            // Retrieve the user name.
            pwszUserName = pHttpUser->GetUserName();
            // Test for an error.
            if (pwszUserName!=NULL)
            {
                // Test for anonymous user.
                if (wcslen(pwszUserName)>0)
                {
                    // Set the flag to indicate an authenticated user.
                    fAuthenticated = TRUE;
                }
            }
        }

        // Test for an authenticated user.
        if (fAuthenticated == FALSE)
        {
            // Clear the existing response.
            pHttpContext->GetResponse()->Clear();
            // Return an access denied message.
            pHttpContext->GetResponse()->SetStatus(401,"Access denied.",0,0);
            // End additional processing.
            return RQ_NOTIFICATION_FINISH_REQUEST;
        }

        g_hFile = CreateFile(TEXT("d:\\inetpub\\wwwroot\\myfile.txt"),
            GENERIC_WRITE,0,NULL,CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
        
        if (g_hFile == INVALID_HANDLE_VALUE) 
        { 
            char szBuffer[256] = "";
            sprintf_s(szBuffer,256,"Could not open file (error %d)\n", GetLastError());
            WriteResponseMessage(pHttpContext,szBuffer);
            return RQ_NOTIFICATION_FINISH_REQUEST;
        }
        else
        {
            OVERLAPPED oOverlapped;
            oOverlapped.hEvent = NULL;
            oOverlapped.Offset = 0;
            oOverlapped.OffsetHigh = 0;
            DWORD dwBytesWritten = 0;
            g_pGlobalInfo->AssociateWithThreadPool(g_hFile,&MyCompletionRoutine);
            //pszUserName = (char*) pHttpContext->AllocateRequestMemory( (DWORD) wcslen(pwszUserName)+1 );
            //wcstombs(pszUserName,pwszUserName,wcslen(pwszUserName));
            //WriteFile(g_hFile, pszUserName, strlen(pszUserName), &dwBytesWritten, &oOverlapped);
            WriteFile(g_hFile, "Hello", strlen("Hello"), &dwBytesWritten, oOverlapped);
            return RQ_NOTIFICATION_PENDING;
        }
    }

private:

    // Create a utility method that inserts a string value into the response.
    HRESULT WriteResponseMessage(
        IHttpContext * pHttpContext,
        PCSTR pszBuffer
    )
    {
        // Create an HRESULT to receive return values from methods.
        HRESULT hr;
        
        // Create a data chunk. (Defined in the Http.h file.)
        HTTP_DATA_CHUNK dataChunk;
        // Set the chunk to a chunk in memory.
        dataChunk.DataChunkType = HttpDataChunkFromMemory;
        // Buffer for bytes written of data chunk.
        DWORD cbSent;

        // Set the chunk to the buffer.
        dataChunk.FromMemory.pBuffer =
            (PVOID) pszBuffer;
        // Set the chunk size to the buffer size.
        dataChunk.FromMemory.BufferLength =
            (USHORT) strlen(pszBuffer);
        // Insert the data chunk into the response.
        hr = pHttpContext->GetResponse()->WriteEntityChunks(
            &dataChunk,1,FALSE,TRUE,&cbSent);
        // Test for an error.
        if (FAILED(hr))
        {
            // Return the error status.
            return hr;
        }

        // Return a success status.
        return S_OK;
    }
};

// Create the module's class factory.
class MyHttpModuleFactory : public IHttpModuleFactory
{
public:
    HRESULT
    GetHttpModule(
        OUT CHttpModule ** ppModule, 
        IN IModuleAllocator * pAllocator
    )
    {
        UNREFERENCED_PARAMETER( pAllocator );

        // Create a new instance.
        MyHttpModule * pModule = new MyHttpModule;

        // Test for an error.
        if (!pModule)
        {
            // Return an error if the factory cannot create the instance.
            return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY );
        }
        else
        {
            // Return a pointer to the module.
            *ppModule = pModule;
            pModule = NULL;
            // Return a success status.
            return S_OK;
        }            
    }

    void Terminate()
    {
        // Remove the class from memory.
        delete this;
    }
};

// Create the module's exported registration function.
HRESULT
__stdcall
RegisterModule(
    DWORD dwServerVersion,
    IHttpModuleRegistrationInfo * pModuleInfo,
    IHttpServer * pGlobalInfo
)
{
    UNREFERENCED_PARAMETER( dwServerVersion );
    UNREFERENCED_PARAMETER( pGlobalInfo );

    // Store the pointer for the global server interface.
    g_pGlobalInfo = pGlobalInfo;

    // Set the request notifications and exit.
    return pModuleInfo->SetRequestNotifications(
        new MyHttpModuleFactory,
        RQ_SEND_RESPONSE,
        0
    );
}

모듈은 RegisterModule 함수를 내보내야 합니다. 프로젝트에 대한 모듈 정의(.def) 파일을 만들어 이 함수를 내보내거나 스위치를 사용하여 모듈을 /EXPORT:RegisterModule 컴파일할 수 있습니다. 자세한 내용은 연습: 네이티브 코드를 사용하여 Request-Level HTTP 모듈 만들기를 참조하세요.

필요에 따라 각 함수에 대한 호출 규칙을 명시적으로 선언하는 대신 호출 규칙을 사용하여 __stdcall (/Gz) 코드를 컴파일할 수 있습니다.

요구 사항

형식 Description
클라이언트 - Windows Vista의 IIS 7.0
- Windows 7의 IIS 7.5
- Windows 8의 IIS 8.0
- WINDOWS 10 IIS 10.0
서버 - Windows Server 2008의 IIS 7.0
- Windows Server 2008 R2의 IIS 7.5
- Windows Server 2012의 IIS 8.0
- Windows Server 2012 R2의 IIS 8.5
- WINDOWS SERVER 2016 IIS 10.0
제품 - IIS 7.0, IIS 7.5, IIS 8.0, IIS 8.5, IIS 10.0
- IIS Express 7.5, IIS Express 8.0, IIS Express 10.0
헤더 Httpserv.h

참고 항목

IHttpServer 인터페이스