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)