使用 SemaphoreSlim 进行线程节流

Thread throttling with SemaphoreSlim

我想确保一次只有一个线程调用该服务,在第一个线程仍在执行时丢弃后面的线程。

  await throttler.WaitAsync();
        T result = default(T);
        HttpResponseMessage response = await Client.Proxy.PostAsJsonAsync(path, request);
        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsAsync<T>();
            throttler.Release();
        }
        else
        {
            throttler.Release();
        }
        return result;

在构造函数中我有 throttler = new System.Threading.SemaphoreSlim(1, 1);

一次只有一个请求被发送到服务器。但是,如果请求仍在执行,我也想终止所有后续请求。

当线程已经在调用服务时,您可以使用 WaitAsync(TimeSpan) 放弃其他调用:

bool entered = await semaphore.WaitAsync(TimeSpan.Zero);
if (entered) {
    try {
        HttpResponseMessage response = await Client.Proxy.PostAsJsonAsync(path, request);
    }
    finally {
        semaphore.Release();
    }
}
else {
    // Discarded: Another service call is in progress    
}