ApiClient
클래스의 여러 소비자가 동시에 호출하는 메서드가 있습니다. 첫 번째 호출이 완료되고 나머지 호출이 단락 될 때까지 메서드에 대한 동시 호출을 차단하고 싶습니다.동시 호출자를 차단하고 비동기 메서드에서 단일 결과를 반환합니다.
아래의 의사 코드에서 여러 스레드가 RefreshApiTokenAsync()
을 호출 할 수 있습니다. 나는 내면 this.GetNewApiTokenAsync()
방법으로 단 하나의 외침을 막고 싶다. 이렇게하면 코드가 여러 스레드에서 만료 된 ApiToken을 감지하고 여러 번 새로 고치려고하는 상황을 피할 수 있습니다.
public class ApiClient
{
private static readonly ConcurrentDictionary<string, string> ApiTokens = new ConcurrentDictionary<string, string>();
public async Task DoSomething()
{
// Call third party API and then detect an out of date API token.
// The CallThirdPartyApi uses the token in the ApiTokens ConcurrentDictionary
var result = await CallThirdPartyApi();
if (result.ApiTokenOutOfDate) {
await this.RefreshApiTokenAsync();
result = await CallThirdPartyApi();
}
return result;
}
private async Task<string> RefreshApiTokenAsync()
{
string newToken = await this.GetNewApiTokenAsync();
return ApiTokens.AddOrUpdate("ApiToken", newToken, (key, value) => newToken);
}
}
나는이 디 바운싱 간주됩니다 생각하지만, 나는이 작업을 수행하는 방법을 잘 모르겠어요.
그것은 소리()'... – Malk
잠금은 여러 스레드를 방지 할 수 GetNewApiTokenAsync를 동시에 호출하지 못하지만 결국에는 모두 호출됩니다. 내가 원하는 것은 GetNewApiTokenAsync에 대한 첫 번째 호출이 발생하지만 실행 중 메서드를 호출하려는 다른 시도는 실제로 무시됩니다. –
'if (locked) return else lockAndRun()' – Malk