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

# 如何使用 XBOX 服务 API (XSAPI)

> 初始化 GRTS、创建 XTaskQueue、设置 HttpClient 跟踪，并调用 XblInitialize 以开始在你的标题中使用 XSAPI C API 进行 XBOX Live 开发。

## 初始化 Gaming Runtime Services

XSAPI 依赖于 Gaming Runtime Services (GRTS)。在调用任何 XSAPI 之前，请先初始化 GRTS，如下所示。

```cpp theme={null}
#include <XGameRuntimeInit.h>
...
HRESULT hr = XGameRuntimeInitialize();
```

## 创建 XTaskQueue（可选）

大多数 XSAPI 都是异步 API，需要使用任务队列。它是一个用于将工作排队和用于完成任务回调的 API。要了解有关 `XTaskQueue` 和不同分派模式的更多信息，请参阅 [异步任务队列设计](/build/core-features/common/async/async-task-queue-design)。

例如，以下代码使用系统线程池创建任务队列。

```cpp theme={null}
#include <XTaskQueue.h>
...
XTaskQueueHandle queue = nullptr;

HRESULT hr = XTaskQueueCreate(
    XTaskQueueDispatchMode::ThreadPool,
    XTaskQueueDispatchMode::ThreadPool,
    &queue)
```

确保在不再需要获取的任务队列句柄时将其释放回系统。

```cpp theme={null}
XTaskQueueCloseHandle(queue);
queue = nullptr;
```

如果你选择不创建自己的任务队列，则在需要队列句柄时请确保传入 `nullptr`。当使用 `nullptr` 时，任务系统默认使用 `ThreadPool`。可以通过调用 [XTaskQueueSetCurrentProcessTaskQueue](/reference/system/xtaskqueue/functions/xtaskqueuesetcurrentprocesstaskqueue) 来重写它。

## 设置 HttpClient 跟踪（可选）

要查看其他运行时调试信息，请确保设置 `HttpClient` 的跟踪功能。

以下代码设置 `HttpClient` 跟踪级别并启用调试器信息的输出。

```cpp theme={null}
HCSettingsSetTraceLevel(HCTraceLevel::Verbose);
HCTraceSetTraceToDebugger(true);
```

## 初始化 XSAPI

在调用任何 XSAPI 之前，*初始化 XSAPI*。

```cpp theme={null}
#include <xsapi-c/services-c.h>
...
XblInitArgs xblArgs = {};
xblArgs.queue = queue; // TODO: Only include this line if you've chosen to create your own XTaskQueue. Otherwise, by default, this line isn't needed.
xblArgs.scid = "00000000-0000-0000-0000-000000000000"; // TODO: Add your scid here.

HRESULT hr = XblInitialize(&xblArgs);
if (FAILED(hr))
{
    // TODO: Handle failure.
}
```

## 将用户登录到 XBOX 网络

大多数 XSAPI 都要求用户先登录到 XBOX 网络（也称为 XBOX Live）。要将用户登录到 XBOX 网络，请参阅 [XUserAddAsync API](/build/core-features/common/user/xuser_howto_best_practice_signing_in) 的代码示例。

## 创建 XboxLiveContext 对象

`XboxLiveContext` 对象表示与特定用户关联的服务上下文。

大多数 XSAPI 要求你传入表示调用用户上下文的 `XboxLiveContextHandle`。要创建 XBOX Live（网络）上下文，请使用 [XblContextCreateHandle API](/reference/live/xsapi-c/xbox_live_context_c/functions/xblcontextcreatehandle)，并传入从上一步获取的 `XUserHandle` 对象。

## 向 XBOX 服务进行服务调用

现在你有了一个与已登录用户的 `XUserHandle` 对象关联的 `XboxLiveContext` 对象，就可以向 XBOX 服务进行服务调用了。

例如，要检索用户的好友列表，你可以执行以下操作：

```cpp theme={null}
#include <xsapi-c/services-c.h>
...
auto asyncBlock = std::make_unique<XAsyncBlock>(); 
asyncBlock->callback = [](XAsyncBlock* asyncBlock)
{
    std::unique_ptr<XAsyncBlock> asyncBlockPtr{ asyncBlock }; // Take over ownership of the XAsyncBlock*.

    XblSocialRelationshipResultHandle relationshipResult{ nullptr };
    HRESULT hr = XblSocialGetSocialRelationshipsResult(asyncBlock, &state.socialResultHandle);

    // Use the result in the game.

    XblSocialRelationshipResultCloseHandle(relationshipResult);
};

HRESULT hr = XblSocialGetSocialRelationshipsAsync(
    xboxLiveContext,
    xboxUserId,
    socialRelationshipFilter,
    0,
    0,
    asyncBlock.get()
);

if (SUCCEEDED(hr))
{
    // The call succeeded. Release the std::unique_ptr ownership of XAsyncBlock* because the callback will take over ownership.
    // If the call fails, the std::unique_ptr will keep ownership and delete the XAsyncBlock*.
    asyncBlock.release();
}
// End of code example.
```

## 清理 XSAPI

在任何场景中，都不必调用 `XblCleanupAsync()`。

在应用程序终止场景中，目前没有可以调用的同步 `XblCleanup()` API。应用程序终止就其生命周期本质而言，需要同步立即处理。因此，依赖于随应用程序进程终止而发生的正常操作系统级清理，这对于此情况已经足够。

在应用程序被挂起的场景中，XSAPI 会处理释放并随后恢复运行所需的系统资源，以便在恢复后保持功能。

在你的游戏选择有意释放分配给 XSAPI 的资源的情况下，仍然可以使用 `XblCleanupAsync()`。


## Related topics

- [获取基于事件的统计信息](/zh-CN/services/xbox-services/player-data/stats-leaderboards/event-based/how-to/live-getting-eb-stat.md)
- [服务器](/zh-CN/services/playfab/multiplayer/servers/index.md)
- [如何使用 XBOX PC Remote 工具](/zh-CN/tools/tools-pc/xbox-pc-remote-tools/how-to-use-tools.md)
- [使用 Fiddler 检查 Web 服务调用](/zh-CN/tools/tools-services/live-fiddler-inspect-web-calls.md)
- [细粒度速率限制](/zh-CN/services/xbox-services/develop/best-practices/live-fine-grained-rate-limiting.md)
