Compartilhar via


Como gerenciar uma instância de agendador

As instâncias do agendador permitem associar políticas específicas de programação com os vários tipos de cargas de trabalho. Este tópico contém dois exemplos básicos que mostram como criar e gerenciar uma instância do agendador.

Os exemplos a seguir cria os agendadores que usam as políticas padrão do agendador. Para obter um exemplo que cria um agendador que usa uma política personalizado, consulte Como especificar políticas de agendador específicas.

Para gerenciar uma instância do agendador no aplicativo

  1. Crie um objeto de concurrency::SchedulerPolicy que contém os valores de política para que o agendador usa.

  2. Chame o método de concurrency::CurrentScheduler::Create ou o método de concurrency::Scheduler::Create para criar uma instância do agendador.

    Se você usar o método de Scheduler::Create , chame o método de concurrency::Scheduler::Attach quando você precisa associar o agendador com o contexto atual.

  3. Chame a função de CreateEvent para criar um identificador em um objeto não sinalizado, redefinido automática do evento.

  4. Passar o identificador do objeto de evento que você acabou de criar a concurrency::CurrentScheduler::RegisterShutdownEvent o método ou o método de concurrency::Scheduler::RegisterShutdownEvent . Isso registra o evento a ser definido quando o agendador é destruído.

  5. Executar as tarefas que você deseja que o agendador atual para agendar.

  6. Chame o método de concurrency::CurrentScheduler::Detach para desanexar o agendador atual e restaurar o agendador anterior como atual.

    Se você usar o método de Scheduler::Create , chame o método de concurrency::Scheduler::Release para diminui a contagem de referência do objeto de Scheduler .

  7. Passar o identificador do evento à função de WaitForSingleObject a esperar para que o agendador para fechar.

  8. Chame a função de CloseHandle para fechar o identificador do objeto de evento.

Exemplo

O código a seguir mostra dois modos de gerenciar uma instância do agendador. Cada exemplo usa basicamente o agendador padrão para executar uma tarefa que imprime em expansão o identificador exclusivo do agendador atual. Cada exemplo usa uma instância do agendador para executar novamente a mesma tarefa. Finalmente, cada exemplo restaura o agendador como padrão atual e executa a tarefa mais uma vez.

O primeiro exemplo usa a classe de concurrency::CurrentScheduler para criar uma instância do agendador e para associá-la ao contexto atual. O segundo exemplo usa a classe de concurrency::Scheduler para executar a mesma tarefa. Normalmente, a classe de CurrentScheduler é usada para trabalhar com o agendador atual. O segundo exemplo, usando a classe de Scheduler , é útil quando você deseja controlar quando o agendador está associado ao contexto atual ou quando você quiser associar agendadores específicos com as tarefas específicas.

// scheduler-instance.cpp 
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <iostream>

using namespace concurrency;
using namespace std;

// Prints the identifier of the current scheduler to the console. 
void perform_task()
{
   // A task group.
   task_group tasks;

   // Run a task in the group. The current scheduler schedules the task.
   tasks.run_and_wait([] { 
      wcout << L"Current scheduler id: " << CurrentScheduler::Id() << endl;
   });
}

// Uses the CurrentScheduler class to manage a scheduler instance. 
void current_scheduler()
{
   // Run the task. 
   // This prints the identifier of the default scheduler.
   perform_task();

   // For demonstration, create a scheduler object that uses  
   // the default policy values.
   wcout << L"Creating and attaching scheduler..." << endl;
   CurrentScheduler::Create(SchedulerPolicy());

   // Register to be notified when the scheduler shuts down.
   HANDLE hShutdownEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
   CurrentScheduler::RegisterShutdownEvent(hShutdownEvent);

   // Run the task again. 
   // This prints the identifier of the new scheduler.
   perform_task();

   // Detach the current scheduler. This restores the previous scheduler 
   // as the current one.
   wcout << L"Detaching scheduler..." << endl;
   CurrentScheduler::Detach();

   // Wait for the scheduler to shut down and destroy itself.
   WaitForSingleObject(hShutdownEvent, INFINITE);

   // Close the event handle.
   CloseHandle(hShutdownEvent);

   // Run the sample task again. 
   // This prints the identifier of the default scheduler.
   perform_task();
}

// Uses the Scheduler class to manage a scheduler instance. 
void explicit_scheduler()
{
   // Run the task. 
   // This prints the identifier of the default scheduler.
   perform_task();

   // For demonstration, create a scheduler object that uses  
   // the default policy values.
   wcout << L"Creating scheduler..." << endl;
   Scheduler* scheduler = Scheduler::Create(SchedulerPolicy());

   // Register to be notified when the scheduler shuts down.
   HANDLE hShutdownEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
   scheduler->RegisterShutdownEvent(hShutdownEvent);

   // Associate the scheduler with the current thread.
   wcout << L"Attaching scheduler..." << endl;
   scheduler->Attach();

   // Run the sample task again. 
   // This prints the identifier of the new scheduler.
   perform_task();

   // Detach the current scheduler. This restores the previous scheduler 
   // as the current one.
   wcout << L"Detaching scheduler..." << endl;
   CurrentScheduler::Detach();

   // Release the final reference to the scheduler. This causes the scheduler 
   // to shut down after all tasks finish.
   scheduler->Release();

   // Wait for the scheduler to shut down and destroy itself.
   WaitForSingleObject(hShutdownEvent, INFINITE);

   // Close the event handle.
   CloseHandle(hShutdownEvent);

   // Run the sample task again. 
   // This prints the identifier of the default scheduler.
   perform_task();
}

int wmain()
{
   // Use the CurrentScheduler class to manage a scheduler instance.
   wcout << L"Using CurrentScheduler class..." << endl << endl;
   current_scheduler();

   wcout << endl << endl;

   // Use the Scheduler class to manage a scheduler instance.
   wcout << L"Using Scheduler class..." << endl << endl;
   explicit_scheduler();
}

O exemplo produz a seguinte saída.

  

Compilando o código

Copie o código de exemplo e cole-o em um projeto do Visual Studio, ou cole-o em um arquivo chamado scheduler-instance.cpp e execute o comando a seguir em uma janela de prompt de comando do Visual Studio.

cl.exe /EHsc scheduler-instance.cpp

Consulte também

Tarefas

Como especificar políticas de agendador específicas

Conceitos

Instâncias de agendador