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

# XUserAddAsync

> XUserAddAsync

# XUserAddAsync

异步将用户添加到游戏会话。

## Syntax

```cpp theme={null}
HRESULT XUserAddAsync(  
         XUserAddOptions options,  
         XAsyncBlock* async  
)  
```

### Parameters

*options*   \_In\_\
类型：[XUserAddOptions](/reference/system/xuser/enums/xuseraddoptions)

用于将用户添加到游戏会话的选项。

*async*   \_Inout\_\
类型：[XAsyncBlock\*](/reference/system/xasync/structs/xasyncblock)

用于轮询调用状态和检索调用结果的 [XAsyncBlock](/reference/system/xasync/structs/xasyncblock)。

### Return value

类型：HRESULT

HRESULT 成功或错误代码。
有关错误代码列表，请参阅[错误代码](/reference/errorcodes)。

## Remarks

**XUserAddAsync** 启动异步操作，将用户添加到游戏。使用 [XUserAddResult](/reference/system/xuser/functions/xuseraddresult) 检索操作结果。

除非将 [XUserAddOptions::AddDefaultUserSilently](/reference/system/xuser/enums/xuseraddoptions) 或 [XUserAddOptions::AddDefaultUserAllowingUI](/reference/system/xuser/enums/xuseraddoptions) 传递给 *options* 参数，否则 **XUserAddAsync** 始终显示帐户选取器 UI。

如果使用 **XUserAddOptions::AddDefaultUserSilently**，则 **XUserAddAsync** 不显示 UI。

使用[简化用户模型（NDA 主题）](/build/core-features/common/user/gamecore-user-models)时，此函数存在一些注意事项：

* 使用简化用户模型时，开发者应确保 *options* 设置为 **XUserAddOptions::AddDefaultUserSilently**：
* 在主机上，除非默认用户已经登录，否则不允许启动使用简化用户模型的松散部署游戏。
* 在 PC 上，可以在没有用户的情况下启动使用简化用户模型的松散部署游戏；但是，当游戏调用 **XUserAddAsync** 时，如果没有人登录，游戏将被终止，PC Bootstrapper 将启动以帮助用户登录。只要用户完全登录到 XBOX Live，后续启动就能正常工作。

如果开发者反复调用 **XUserAddAsync** 并将 *options* 设置为 **XUserAddOptions::AddDefaultUserSilently**，则应了解一些边缘情况：

* 如果反复调用此项，并且我们知道启动游戏的默认用户，它将返回相同的用户。
* 如果先前已知的默认用户已注销，并且只有一个用户登录设备，它会将该用户标记为新的“默认”用户并返回。
* 如果先前已知的默认用户已注销，并且有多个用户登录设备，它将返回 E\_GAMEUSER\_NO\_DEFAULT\_USER。

如果默认用户不可用，[XUserAddResult](/reference/system/xuser/functions/xuseraddresult) 将返回 E\_GAMEUSER\_NO\_DEFAULT\_USER。必须调用 **XUserAddAsync**，并且 *options* 不设置为 **XUserAddOptions::AddDefaultUserSilently**。

如果开发者反复调用 **XUserAddAsync** 并将 *options* 设置为 **XUserAddOptions::AddDefaultUserAllowingUI**，也应了解一些边缘情况。这些情况与静默 UI 情况非常相似（但不完全相同）：

* 如果反复调用此项，并且我们知道启动游戏的默认用户，它将返回相同的用户。
* 如果先前已知的默认用户已注销，并且只有一个用户登录设备，它会将该用户标记为新的“默认”用户并返回。
* 如果最初启动游戏的用户已注销，并且用户数为 0 或多于 1，则系统将显示 UI 以获取用户，然后将该用户设置为默认。

不能将 [XUserAddOptions::AllowGuests](/reference/system/xuser/enums/xuseraddoptions) 与 **XUserAddOptions::AddDefaultUserSilently** 一起使用。来宾不能是默认用户。无论当前平台是否支持来宾，都可以安全地使用 **XUserAddOptions::AllowGuests**。

必须通过调用 [XUserCloseHandle](/reference/system/xuser/functions/xuserclosehandle) 仅关闭一次从 **XUsers** API 检索到的每个 **XUserHandle** 句柄。

输入设备配对是在 **XUserAddAsync** 成功完成后执行的。如果由于 **XUserAddOptions::AddDefaultUserSilently** 或 **XUserAddOptions::AddDefaultUserAllowingUI** 选项而自动登录且无 UI，则将系统中分配给该用户的输入设备传播到标题。如果显示了登录 UI，则选定该用户的输入设备将分配给该用户。

可以通过 [XUserRegisterForDeviceAssociationChanged](/reference/system/xuser/functions/xuserregisterfordeviceassociationchanged) 方法跟踪设备关联。

以下示例演示了如何异步地将用户添加到游戏会话。

```cpp theme={null}
HRESULT AddUserComplete(XAsyncBlock* ab)
{
    unique_user_handle user;
    RETURN_IF_FAILED(XUserAddResult(ab, &user));

    XUserLocalId userLocalId;
    XUserGetLocalId(user.get(), &userLocalId);

    auto iter = std::find_if(
        _users.begin(),
        _users.end(),
        [&userLocalId](const User& candidate)
    {
        XUserLocalId candidateUserLocalId;
        XUserGetLocalId(candidate.Handle(), &candidateUserLocalId);
        return candidateUserLocalId == userLocalId;
    });

    // User already known
    if (iter != _users.end())
    {
        appLog.AddLog("User already in list\n");
        return S_OK;
    }

    try
    {
        _users.emplace_back(user.get());
        _users.back().LoadGamerPicAsync(_queue);
    }
    CATCH_RETURN();

    return S_OK;
}

HRESULT AddUser(bool allowGuests, bool silent)
{
    auto asyncBlock = std::make_unique<XAsyncBlock>();
    ZeroMemory(asyncBlock.get(), sizeof(*asyncBlock));
    asyncBlock->queue = _queue;
    asyncBlock->context = this;
    asyncBlock->callback = [](XAsyncBlock* ab)
    {
        auto asyncBlock = std::unique_ptr<XAsyncBlock>(ab);
        LOG_IF_FAILED(static_cast<UserWindow*>(ab->context)->AddUserComplete(ab));
    };

    XUserAddOptions options = XUserAddOptions::None;

    if (allowGuests)
    {
        WI_SET_FLAG(options, XUserAddOptions::AllowGuests);
    }

    if (silent)
    {
        WI_SET_FLAG(options, XUserAddOptions::AddDefaultUserSilently);
    }

    if (SUCCEEDED_LOG(XUserAddAsync(
        options,
        asyncBlock.get())))
    {
        // The call succeeded, so release the std::unique_ptr ownership of XAsyncBlock* since the callback will take over ownership.
        // If the call fails, the std::unique_ptr will keep ownership and delete the XAsyncBlock*
        asyncBlock.release();
    }

    return S_OK;
}
```

## Requirements

**头文件：** XUser.h

**库：** xgameruntime.lib

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

## Conceptual documentation

* [运行 Microsoft Game Development Kit (GDK) API 任务](/build/core-features/common/async/async-libraries/async-library-xasync-example-run-gdk-task)
* [异步编程设计目标和改进](/build/core-features/common/async/async-whitepaper)
* [在游戏中实现玩家登录](https://learn.microsoft.com/gaming/gdk/docs/gdk-dev/pc-dev/tutorials/pc-e2e-guide/e2e-services/e2e-user-sign-in)
* [Game Chat 2 简介](/services/xbox-services/multiplayer/chat/game-chat2/game-chat-2-intro)
* [使用 Game Chat 2 C++ API](/services/xbox-services/multiplayer/chat/game-chat2/using-game-chat-2)
* [实现玩家登录](https://learn.microsoft.com/gaming/gdk/docs/services/playfab-integration/gdk-playfab-player-sign-in-steps)

## See also

[XUser](/reference/system/xuser/xuser_members)

[XUserAddOptions](/reference/system/xuser/enums/xuseraddoptions)

[XUserCloseHandle](/reference/system/xuser/functions/xuserclosehandle)


## Related topics

- [XUserAddOptions](/zh-CN/reference/system/xuser/enums/xuseraddoptions.md)
- [XUserAddResult](/zh-CN/reference/system/xuser/functions/xuseraddresult.md)
- [面向 GDK 的 Unity C# API 包装器](/zh-CN/build/gdk-and-engines/unity/unity-api-wrappers.md)
- [用户身份与 XUser](/zh-CN/build/core-features/common/user/player-identity-xuser.md)
- [登录和沙盒错误故障排除](/zh-CN/services/xbox-services/develop/troubleshooting/live-troubleshoot-sandboxes.md)
