/// <summary> /// Checks the current <see cref="HttpClient"/> and replaces it if headers or <see cref="Handler"/> has been modified /// </summary> protected (HttpClient Client, IDisposable Lock) GetClient() { // return current client if there are no changes var resetLevel = Interlocked.Exchange(ref _clientAdjustmentRequestSignal, 0); if (resetLevel > 0) { // block all reads and let all current requests finish using (_lock.WriterLock()) { // only reset the client if the handler has changed (signal = 2) var resetClient = resetLevel == 2; if (resetClient) { var handler = CreateHandler(); Client?.Dispose(); Client = handler != null ? new HttpClient(handler, true) : new HttpClient(); } // apply new headers Headers.ApplyTo(Client); // allow the consumer to change the client SetupClient(Client, resetClient); // reset the state Interlocked.Exchange(ref _clientAdjustmentRequestSignal, 0); } } return(Client, _lock.ReaderLock()); }