Compartir a través de


IHttpContext::GetCurrentExecutionStats (Método)

Recupera las estadísticas de ejecución del contexto actual.

Sintaxis

virtual HRESULT GetCurrentExecutionStats(  
   DWORD* pdwNotification,  
   DWORD* pdwNotificationStartTickCount = NULL,  
   PCWSTR* ppszModule = NULL,  
   DWORD* pdwModuleStartTickCount = NULL,  
   DWORD* pdwAsyncNotification = NULL,  
   DWORD* pdwAsyncNotificationStartTickCount = NULL  
) const = 0;  

Parámetros

pdwNotification
Puntero a un DWORD objeto que contiene la notificación actual.

pdwNotificationStartTickCount
Puntero a un DWORD objeto que contiene el recuento de tics para el inicio de la notificación actual.

ppszModule
Puntero a una cadena que contiene el nombre del módulo actual.

pdwModuleStartTickCount
Puntero a un DWORD objeto que contiene el recuento de tics para el inicio del módulo actual.

pdwAsyncNotification
Puntero a un DWORD objeto que contiene la notificación asincrónica actual.

pdwAsyncNotificationStartTickCount
Puntero a un DWORD objeto que contiene el recuento de tics para el inicio de una notificación asincrónica.

Valor devuelto

Una clase HRESULT. Entre los valores posibles se incluyen los que se indican en la tabla siguiente, entre otros.

Valor Descripción
NO_ERROR Indica que la operación se realizó correctamente.
E_INVALIDARG Indica que un parámetro especificado no es válido.

Comentarios

Los desarrolladores pueden usar el GetCurrentExecutionStats método para recuperar información de ejecución específica para el contexto actual. Por ejemplo, los pdwNotification parámetros y pdwAsyncNotification contienen los valores de la notificación sincrónica o asincrónica actual, y el ppszModule parámetro contiene el nombre del módulo para el contexto actual.

Tres de los parámetros devueltos, pdwModuleStartTickCount, pdwNotificationStartTickCounty pdwAsyncNotificationStartTickCount, respectivamente, contienen los recuentos de tics para el inicio del módulo y el inicio de las notificaciones sincrónicas y asincrónicas actuales.

Nota

El recuento de tics es el número de milisegundos que han transcurrido desde que se inició el sistema. Para obtener más información sobre cómo recuperar recuentos de tics, vea el método GetTickCount .

Ejemplo

En el ejemplo de código siguiente se muestra cómo crear un módulo HTTP que realice las tareas siguientes:

  1. El módulo se registra para las notificaciones de RQ_BEGIN_REQUEST, RQ_MAP_REQUEST_HANDLER y RQ_SEND_RESPONSE .

  2. El módulo crea una clase CHttpModule que contiene métodos OnBeginRequest, OnMapRequestHandler y OnSendResponse .

  3. Cuando un cliente web solicita una dirección URL, IIS llama a los métodos , OnMapRequestHandlery OnSendResponse del OnBeginRequestmódulo. Cada uno de estos métodos llama a un método privado denominado RetrieveExecutionStats que realiza las tareas siguientes:

    1. Recupera las estadísticas de ejecución mediante el GetCurrentExecutionStats método y comprueba si hay un error.

    2. Crea una cadena que contiene el recuento de tics para el inicio de la notificación actual.

    3. Se detiene durante un segundo.

    4. Crea una cadena que contiene el recuento de tics transcurridos desde el inicio de la notificación actual.

    5. Escribe las estadísticas de ejecución como un evento en el registro de la aplicación del Visor de eventos.

  4. El módulo quita la CHttpModule clase de la memoria y, a continuación, se cierra.

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

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

    // Create a handle for the event viewer.
    HANDLE m_hEventLog;

    // Define a method the retrieves the current execution statistics.
    void RetrieveExecutionStats(
        IHttpContext * pHttpContext, LPCSTR szNotification )
    {
        HRESULT hr = S_OK;
        DWORD  dwNotification = 0;
        DWORD  dwNotificationStart = 0;
        PCWSTR pszModule = NULL;

        // Retrieve the current execution statistics.
        hr = pHttpContext->GetCurrentExecutionStats(
            &dwNotification,&dwNotificationStart,
            &pszModule,NULL,NULL,NULL);

        // Test for an error.
        if (SUCCEEDED(hr))
        {
            // Create strings for the statistics.
            char szNotificationStart[256];
            char szTimeElapsed[256];
            
            // Retrieve and format the statistics.
            sprintf_s(szNotificationStart,255,
                "Tick count at start of notification: %u",
                dwNotificationStart);
            // Pause for one second.
            Sleep(1000);
            // Retrieve and format the statistics.
            sprintf_s(szTimeElapsed,255,
                "Ticks elapsed since start of notification: %u",
                GetTickCount() - dwNotificationStart);
            
            // Allocate space for the module name.
            char * pszBuffer = (char*) pHttpContext->AllocateRequestMemory(
                (DWORD) wcslen(pszModule)+1 );
            
            // Test for an error.
            if (pszBuffer!=NULL)
            {
                // Return the module information to the web client.
                wcstombs(pszBuffer,pszModule,wcslen(pszModule));
                // Create an array of strings.
                LPCSTR szBuffer[4] = {szNotification,pszBuffer,
                    szNotificationStart,szTimeElapsed};
                // Write the strings to the Event Viewer.
                WriteEventViewerLog(szBuffer,4);
            }
        }
    }

public:

    REQUEST_NOTIFICATION_STATUS
    OnBeginRequest(
        IN IHttpContext * pHttpContext,
        IN IHttpEventProvider * pProvider
    )
    {
        UNREFERENCED_PARAMETER( pProvider );
        // Retrieve and return the execution statistics.
        RetrieveExecutionStats(pHttpContext,"OnBeginRequest");
        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }

    REQUEST_NOTIFICATION_STATUS
    OnMapRequestHandler(
        IN IHttpContext * pHttpContext,
        IN IMapHandlerProvider * pProvider
    )
    {
        UNREFERENCED_PARAMETER( pProvider );
        // Retrieve and return the execution statistics.
        RetrieveExecutionStats(pHttpContext,"OnMapRequestHandler");
        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }

    REQUEST_NOTIFICATION_STATUS
    OnSendResponse(
        IN IHttpContext * pHttpContext,
        IN ISendResponseProvider * pProvider
    )
    {
        UNREFERENCED_PARAMETER( pProvider );
        // Retrieve and return the execution statistics.
        RetrieveExecutionStats(pHttpContext,"OnSendResponse");
        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }

    MyHttpModule()
    {
        // Open a handle to the Event Viewer.
        m_hEventLog = RegisterEventSource( NULL,"IISADMIN" );
    }

    ~MyHttpModule()
    {
        // Test whether the handle for the Event Viewer is open.
        if (NULL != m_hEventLog)
        {
            // Close the handle to the Event Viewer.
             DeregisterEventSource( m_hEventLog );
            m_hEventLog = NULL;
        }
    }

private:

    // Define a method that writes to the Event Viewer.
    BOOL WriteEventViewerLog(LPCSTR * lpStrings, WORD wNumStrings)
    {
        // Test whether the handle for the Event Viewer is open.
        if (NULL != m_hEventLog)
        {
            // Write any strings to the Event Viewer and return.
            return ReportEvent(
                m_hEventLog, EVENTLOG_INFORMATION_TYPE,
                0, 0, NULL, wNumStrings, 0, lpStrings, NULL );
        }
        return FALSE;
    }
};

// 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 we 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 );

    return pModuleInfo->SetRequestNotifications(
        new MyHttpModuleFactory,
        RQ_BEGIN_REQUEST | RQ_MAP_REQUEST_HANDLER | RQ_SEND_RESPONSE,
        0
    );
}

El módulo debe exportar la función RegisterModule . Puede exportar esta función mediante la creación de un archivo de definición de módulo (.def) para el proyecto, o bien puede compilar el módulo mediante el /EXPORT:RegisterModule modificador . Para obtener más información, vea Tutorial: Creación de un módulo HTTP de Request-Level mediante código nativo.

Opcionalmente, puede compilar el código mediante la __stdcall (/Gz) convención de llamada en lugar de declarar explícitamente la convención de llamada para cada función.

Requisitos

Tipo Descripción
Remoto - IIS 7.0 en Windows Vista
- IIS 7.5 en Windows 7
- IIS 8.0 en Windows 8
- IIS 10.0 en Windows 10
Servidor - IIS 7.0 en Windows Server 2008
- IIS 7.5 en Windows Server 2008 R2
- IIS 8.0 en Windows Server 2012
- IIS 8.5 en Windows Server 2012 R2
- IIS 10.0 en Windows Server 2016
Producto - 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
Encabezado Httpserv.h

Consulte también

IHttpContext (interfaz)