示例
你可能希望显式控制用于任务队列工作和完成回调的线程。在这些情况下,可创建一个手动任务队列并自行分派调用。如果你使用手动任务队列,必须确保它们也同时泵送 Windows 消息队列。 以下示例展示了如何创建一个手动泵送的任务队列。它创建了两个 STL 线程,分别为工作端口和完成端口分派调用。void CreatingTaskQueueWithManualThreads()
{
// Create a manual task queue.
XTaskQueueHandle queue;
HRESULT hr = XTaskQueueCreate(
XTaskQueueDispatchMode::Manual,
XTaskQueueDispatchMode::Manual,
&queue);
if (FAILED(hr))
{
printf("Creating queue failed: 0x%x\r\n", hr);
return;
}
// We create threads to pump the queue: one thread for the work port
// and one thread for the completion port.
std::thread workThread([queue]
{
// XTaskQueueDispatch returns false when there's nothing to
// dispatch. Here, we wait forever for something new to come
// in. This will return false only if the queue is being
// terminated.
while (XTaskQueueDispatch(queue, XTaskQueuePort::Work, INFINITE));
});
std::thread completionThread([queue]
{
// XTaskQueueDispatch returns false when there's nothing to
// dispatch. Here, we wait forever for something new to come
// in. This will return false only if the queue is being
// terminated.
while (XTaskQueueDispatch(queue, XTaskQueuePort::Completion, INFINITE));
});
SubmitCallbacks(queue);
// Wait a while for the callbacks to run.
Sleep(1000);
// Terminating the queue will cause a waiting XTaskQueueDispatch to return
// false.
XTaskQueueTerminate(queue, true, nullptr, nullptr);
workThread.join();
completionThread.join();
}
