> ## 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.

# XTaskQueueTerminate

> XTaskQueueTerminate

# XTaskQueueTerminate

通过取消所有挂起项并阻止将新项排入队列来终止任务队列。

## Syntax

```cpp theme={null}
HRESULT XTaskQueueTerminate(  
         XTaskQueueHandle queue,  
         bool wait,  
         void* callbackContext,  
         XTaskQueueTerminatedCallback* callback  
)  
```

### Parameters

*queue*   \_In\_\
类型：XTaskQueueHandle

要终止的队列。

*wait*   \_In\_\
类型：bool

True 表示等待终止完成。

*callbackContext*   \_In\_opt\_\
类型：void\*

要传递给回调的可选上下文指针。

*callback*   \_In\_opt\_\
类型：XTaskQueueTerminatedCallback\*

可选回调，将在队列终止时调用。

### Return value

类型：HRESULT

HRESULT 成功或错误代码。

## Remarks

<Note>此函数在时间敏感线程上调用不安全。有关详细信息，请参阅[时间敏感线程](https://learn.microsoft.com/gaming/gdk/docs/gdk-dev/console-dev/overviews/threads/time-sensitive-threads)。</Note>

[XTaskQueueCloseHandle](/reference/system/xtaskqueue/functions/xtaskqueueclosehandle) 只是递减任务队列对象上的内部引用计数。如果队列中仍有回调，这些回调会保持对队列对象的引用，它们仍可能被调用。这可能会给应用程序关闭带来问题。当应用程序关闭时，需要确保清理后不会执行任何虚假回调。XTaskQueue 提供 **XTaskQueueTerminate** API 来对队列执行受控终止。

终止任务队列会执行以下操作：

1. 两个端口的所有回调都将在其 *canceled* 参数设置为 true 的情况下被调用。
2. 工作端口上的所有挂起回调将被调度。向工作端口提交新回调将失败并返回 E\_ABORT。
3. 完成端口上的所有挂起回调将被调度。向完成端口提交新回调将失败并返回 E\_ABORT。

在此过程完成后，如果 wait 为 true，**XTaskQueueTerminate** 将返回。如果 wait 为 false，则终止是异步发生的。如果提供终止回调，将在终止结束时从完成线程调用它。

<Note />

* **XTaskQueueTerminate** 不会关闭队列句柄。终止之后，仍需要调用 [XTaskQueueCloseHandle](/reference/system/xtaskqueue/functions/xtaskqueueclosehandle)。
* 如果在通过调用 [XTaskQueueDispatch](/reference/system/xtaskqueue/functions/xtaskqueuedispatch) 为队列回调提供服务的线程上调用 **XTaskQueueTerminate**，请勿将 wait 参数传入 true，否则代码可能会死锁。

以下示例演示了如何终止先前创建的任务队列。

<Note>**SubmitCallback** 是在 [XTaskQueueSubmitCallback](/reference/system/xtaskqueue/functions/xtaskqueuesubmitcallback) 函数的代码示例中定义的帮助程序函数。</Note>

```cpp theme={null}
void CreatingTaskQueue()
{
    XTaskQueueHandle queue;
    HRESULT hr = XTaskQueueCreate(XTaskQueueDispatchMode::ThreadPool, XTaskQueueDispatchMode::ThreadPool, &queue);
    if (FAILED(hr))
    {
        printf("Creating queue failed: 0x%x\r\n", hr);
        return;
    }

    SubmitCallbacks(queue);

    // Wait a while for the callbacks to run
    Sleep(1000);

    XTaskQueueTerminate(queue, true, nullptr, nullptr);
}
```

任务队列可以与 UI 线程集成。通常，你希望排队到完成端口的回调在 UI 线程上运行。此示例使用线程池执行工作，但将完成端口回调集成到 Win32 Window Proc 中。它还演示了在将任务队列与另一种线程模型集成时正确终止任务队列的方法。

```cpp theme={null}
struct WorkData
{
    HWND hwnd;
    WCHAR text[80];
};

void CALLBACK WorkCompletion(void* context, bool cancel)
{
    WorkData* data = (WorkData*)context;

    if (!cancel)
    {
        SetWindowText(data->hwnd, data->text);
    }

    delete data;
}

void CALLBACK BackgroundWork(void* context, bool cancel)
{
    if (!cancel)
    {
        WorkData* data = new WorkData;
        data->hwnd = (HWND)context;

        if (GetTimeFormatEx(
            LOCALE_NAME_USER_DEFAULT, 0, nullptr, 
            nullptr, data->text, 80) == 0)
        {
            swprintf_s(data->text, L"Error : %d", GetLastError());
        }

        // Now take our formatted string and submit it as a completion callback
        XTaskQueueSubmitCallback(
            g_queue,
            XTaskQueuePort::Completion, 
            data, 
            WorkCompletion);
    }
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    HRESULT hr;

    switch (msg)
    {
    case WM_CREATE:
        
        // We will do work on the thread pool, but completion
        // callbacks should be manual so we can integrate them with
        // the message loop.

        hr = XTaskQueueCreate(
            XTaskQueueDispatchMode::ThreadPool,
            XTaskQueueDispatchMode::Manual,
            &g_queue);

        if (SUCCEEDED(hr))
        {
            hr = XTaskQueueRegisterMonitor(g_queue, hwnd, 
                [](void* context, XTaskQueueHandle, XTaskQueuePort port)
            {
                // If a new callback was submitted to the completion port, post a message
                // so we dispatch it in our message loop
                if (port == XTaskQueuePort::Completion)
                {
                    HWND hwnd = static_cast<HWND>(context);
                    PostMessage(hwnd, WM_QUEUE_COMPLETION, 0, 0);
                }
            }, &g_monitorToken);
        }

        if (FAILED(hr))
        {
            PostQuitMessage(1);
            return 0;
        }
        break;
      
    case WM_LBUTTONDOWN:
        hr = XTaskQueueSubmitCallback(
            g_queue,
            XTaskQueuePort::Completion,
            hwnd,
            BackgroundWork);

        if (FAILED(hr))
        {
            MessageBox(hwnd, L"Failed to submit callback.", L"Error", MB_OK);
        }
        break;

    case WM_QUEUE_COMPLETION:
        XTaskQueueDispatch(g_queue, XTaskQueuePort::Completion, 0);
        break;

    case WM_CLOSE:

        // Terminate the task queue.  When done, destroy our window.  The termination callback
        // is queued to the completion port, so it will already be on the UI thread.

        hr = XTaskQueueTerminate(g_queue, false, hwnd, [](void* context)
        {
            HWND hwnd = static_cast<HWND>(context);
            DestroyWindow(hwnd);
            XTaskQueueUnregisterMonitor(g_queue, g_monitorToken);
            XTaskQueueCloseHandle(g_queue);
        });

        if (SUCCEEDED(hr))
        {
            // Prevent DefWndProc from destroying our window because
            // the termination callback will do it.
            return 0;
        }
        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    }

    return DefWindowProc(hwnd, msg, wParam, lParam);
}

void TestWndProc()
{
    WNDCLASS wndClass;
    ZeroMemory(&wndClass, sizeof(wndClass));
    wndClass.lpfnWndProc = WndProc;
    wndClass.lpszClassName = L"TestClass";
    wndClass.hInstance = GetModuleHandle(nullptr);
    wndClass.hbrBackground = GetSysColorBrush(COLOR_WINDOW);

    ATOM c = RegisterClass(&wndClass);

    HWND h = CreateWindow(L"TestClass", L"Window", 
        WS_OVERLAPPEDWINDOW | WS_VISIBLE, 
        10, 10, 300, 100, nullptr, nullptr, 
        GetModuleHandle(nullptr), 0);

    if (!h)
    {
        return;
    }

    MSG m;

    while (GetMessage(&m, nullptr, 0, 0))
    {
        TranslateMessage(&m);
        DispatchMessage(&m);
    }
}
```

## Requirements

**头文件：** XTaskQueue.h

**库：** xgameruntime.lib

**受支持的平台：** Windows、XBOX One 系列主机和 XBOX Series 主机

## Conceptual documentation

* [清理任务队列](/build/core-features/common/async/async-libraries/async-library-xtaskqueue-example-cleanup-task-queue)
* [时间敏感线程](https://learn.microsoft.com/gaming/gdk/docs/gdk-dev/console-dev/overviews/threads/time-sensitive-threads)

## See also

[XTaskQueue 成员](/reference/system/xtaskqueue/xtaskqueue_members)\
[异步编程模型](/build/core-features/common/async/async-programming-model)\
[异步任务队列设计](/build/core-features/common/async/async-task-queue-design)


## Related topics

- [XTaskQueueTerminatedCallback](/zh-CN/reference/system/xtaskqueue/functions/xtaskqueueterminatedcallback.md)
- [XTaskQueueCloseHandle](/zh-CN/reference/system/xtaskqueue/functions/xtaskqueueclosehandle.md)
- [XTaskQueueCallback](/zh-CN/reference/system/xtaskqueue/functions/xtaskqueuecallback.md)
- [XTaskQueue](/zh-CN/reference/system/xtaskqueue/xtaskqueue_members.md)
- [清理任务队列示例](/zh-CN/build/core-features/common/async/async-libraries/async-library-xtaskqueue-example-cleanup-task-queue.md)
