在异步方法中使用信号量会导致 WPF 调度程序线程死锁吗?

Can the usage of a Semaphore in async methods lead to deadlocks on WPF dispatcher thread?

我从 System.Net.HttpClient class 派生来实现一个处理令牌检索和刷新的客户端。客户端使用所有必需的身份验证参数进行初始化,并且可能会同时使用。在那种情况下,我需要阻止客户端请求多个令牌(针对不同的请求)。

我不确定如果用户在调度程序线程上启动多个 Web 请求(因为信号量是不可重入的,因此调度程序线程 可能会导致 WPF 应用程序出现死锁 在等待信号量时被阻塞,如果调度程序线程被阻塞,原始任务可能无法完成)。

public class ApiClient : HttpClient
{
    public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (_token == null)
        {
            await _semaphore.WaitAsync(cancellationToken);
            try
            {
                if (_token == null)
                {
                    // _token = await _tokenService.AcquireToken(xx,xx,xx);
                }
            }
            finally
            {
                _semaphore.Release();
            }
        }
        else if (_token.IsExpired)
        {
            await _semaphore.WaitAsync(cancellationToken);
            try
            {
                if (_token.IsExpired)
                {
                    // _token = await _tokenService.RefreshToken(xx,xx,xx);
                }
            }
            finally
            {
                _semaphore.Release();
            }
        }
        return await base.SendAsync(request, cancellationToken);
    }
}

the dispatcher thread might be blocked while waiting on the semaphore

您显示的代码不会发生这种情况。它使用异步等待(await),所以线程不会被阻塞。