> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何：创建手动任务队列

> 如何：创建手动任务队列

## 示例

你可能希望显式控制用于任务队列工作和完成回调的线程。在这些情况下，可创建一个*手动任务队列*并自行分派调用。如果你使用手动任务队列，必须确保它们也同时泵送 Windows 消息队列。

以下示例展示了如何创建一个手动泵送的任务队列。它创建了两个 STL 线程，分别为工作端口和完成端口分派调用。

```c++ theme={null}
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();  
}  
```

## 另请参阅

[设计任务队列](/build/core-features/common/async/async-task-queue-design)


## Related topics

- [如何：创建复合任务队列](/zh-CN/build/core-features/common/async/async-task-queue-design-howto/creating-composite-task-queue.md)
- [如何：创建线程池任务队列](/zh-CN/build/core-features/common/async/async-task-queue-design-howto/creating-thread-pool-task-queue.md)
- [异步任务队列设计](/zh-CN/build/core-features/common/async/async-task-queue-design.md)
- [XTaskQueueDispatchMode](/zh-CN/reference/system/xtaskqueue/enums/xtaskqueuedispatchmode.md)
- [创建任务队列示例](/zh-CN/build/core-features/common/async/async-libraries/async-library-xtaskqueue-example-create-task-queue.md)
