小编Cat*_*een的帖子

为什么 SemaphoreSlim.WaitAsync 不起作用?在 GetAccesTokenAsync 调用完成之前它会跳转到“return currentToken.AccessToken”

SemaphoreSlim.WaitAsync不管用。它跳转到调用完成return currentToken.AccessToken之前并抛出 NullException。GetAccesTokenAsync我也尝试使用 AsyncLock、AsyncSemaphore 和我在网上阅读的其他一些方法,但它似乎对我的情况不起作用。

public static class HttpClientHelper
{
    #region members
    private static SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
    private static Token currentToken;
    #endregion

    public static string GetAuthorizeToken(ref HttpClient client, string username, string password)
    {
        GetToken(client, username, password);

        return currentToken.AccessToken;
    }

    private static async void GetToken(HttpClient client, string username, string password)
    {
        await semaphore.WaitAsync();

        try
        {
            if (currentToken == null)
            {
                await GetAccesTokenAsync(client, username, password);
            }
            else if (currentToken.IsExpired)
            {
                await GetAccessTokenByRefreshToken(client);
            }
        } …
Run Code Online (Sandbox Code Playgroud)

c# synchronization semaphore async-await

5
推荐指数
1
解决办法
5814
查看次数

标签 统计

async-await ×1

c# ×1

semaphore ×1

synchronization ×1