gpt4 book ai didi

c# - 为什么 SemaphoreSlim.WaitAsync 不起作用?它在 GetAccesTokenAsync 调用完成之前跳转到 "return currentToken.AccessToken"

转载 作者:行者123 更新时间:2023-12-04 14:12:09 26 4
gpt4 key购买 nike

SemaphoreSlim.WaitAsync不管用。它跳转到 return currentToken.AccessToken之前GetAccesTokenAsync调用它已完成并抛出 NullException。我还尝试使用 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);
}
}
finally
{
semaphore.Release();
}
}

private static async Task<Token> GetAccesTokenAsync(HttpClient client, string username, string password)
{
List<KeyValuePair<string, string>> requestBody = new List<KeyValuePair<string, string>>();
requestBody.Add(new KeyValuePair<string, string>("Username", username));
requestBody.Add(new KeyValuePair<string, string>("Password", password));
requestBody.Add(new KeyValuePair<string, string>("grant_type", "password"));

try
{
using (var urlEncodedContent = new FormUrlEncodedContent(requestBody))
{
var httpResponse = await client.PostAsync(new Uri(client.BaseAddress + "/api/authentication/token"), urlEncodedContent);
currentToken = await httpResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() });
}

return currentToken;
}
catch (Exception e)
{
Logers.Log.Error($"Error while getting the access token {e}");
return null;
}
}
}

最佳答案

您需要做的第一件事是更改您的 private static async void GetToken()返回任务的方法声明:private static async Task GetToken() .如果它不返回任务,您将无法等待它完成。 (正如 GSerg 所说,“async void”是“即发即忘”。)
从同步方法调用异步方法的最基本方法是使用 Task.Run(...).Wait() , 如下所示。
注意拨打Task.Run(waitForSem).Wait();这实际上是将异步调用转换为同步调用。

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
static void Main()
{
Parallel.Invoke(() => timeWaitForSem(1), () => timeWaitForSem(2));
Console.ReadLine();
}

static void timeWaitForSem(int id)
{
var sw = Stopwatch.StartNew();
Console.WriteLine($"Thread {id} is waiting for semaphore.");
Task.Run(waitForSem).Wait(); // <=== HERE is the important bit.
Console.WriteLine($"Thread {id} finished waiting for semaphore after {sw.Elapsed}.");
}

static async Task waitForSem()
{
await _semaphore.WaitAsync().ConfigureAwait(false);
// Keep hold of the semaphore for a while.
await Task.Delay(2000).ConfigureAwait(false);
_semaphore.Release();
}

static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
}
}
该程序的输出将类似于:
Thread 1 is waiting for semaphore.
Thread 2 is waiting for semaphore.
Thread 1 finished waiting for semaphore after 00:00:02.0133882.
Thread 2 finished waiting for semaphore after 00:00:04.0316629.
你不能做的是简单地输入 waitForSem().Wait();而不是 Task.Run(waitForSem).Wait(); ,因为您很可能会以这种方式陷入死锁(尤其是从具有消息泵的应用程序(例如 WinForms)调用它时)。
如需更多信息,请参阅 Calling async methods from non-async code
另一种更有效的方法是使用 JoinableTaskFactory来自 Microsoft.VisualStudio.Threading.dll .要使用它,您需要引用 Microsoft.VisualStudio.Threading.dll或通过 NuGet 添加。
这具有在不需要时不启动新线程的优点。如果您使用 JoinableTaskFactory ,代码如下所示:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Threading;

namespace ConsoleApp1
{
class Program
{
static void Main()
{
Parallel.Invoke(() => timeWaitForSem(1), () => timeWaitForSem(2));
Console.ReadLine();
}

static void timeWaitForSem(int id)
{
var sw = Stopwatch.StartNew();
Console.WriteLine($"Thread {id} is waiting for semaphore.");

_jtf.Run(async () => await waitForSem().ConfigureAwait(false));

Console.WriteLine($"Thread {id} finished waiting for semaphore after {sw.Elapsed}.");
}

static async Task waitForSem()
{
await _semaphore.WaitAsync().ConfigureAwait(false);
// Keep hold of the semaphore for a while.
await Task.Delay(2000).ConfigureAwait(false);
_semaphore.Release();
}

static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
static readonly JoinableTaskFactory _jtf = new JoinableTaskFactory(new JoinableTaskContext());
}
}

关于c# - 为什么 SemaphoreSlim.WaitAsync 不起作用?它在 GetAccesTokenAsync 调用完成之前跳转到 "return currentToken.AccessToken",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63503496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com