Esempio n. 1
0
        public Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, HttpCompletionOption option, CancellationToken token)
        {
            #if NET_3_5
            if(_connectionCount >= _connectionLimit) {
                return Task.Delay(500).ContinueWith(t => SendAsync(message, option, token)).Unwrap();
            }

            Interlocked.Increment(ref _connectionCount);
            #else
            return _sendSemaphore?.WaitAsync()?.ContinueWith(t =>
            {
            #endif
                var challengeResponseAuth = Authenticator as IChallengeResponseAuthenticator;
                if (challengeResponseAuth != null) {
                    _authHandler.Borrow(x => x.Authenticator = challengeResponseAuth);
                    challengeResponseAuth.PrepareWithRequest(message);
                }

                var httpClient = default(HttpClient);
                if(!_httpClient.AcquireTemp(out httpClient)) {
                    return null;
                }


                (Authenticator as ICustomHeadersAuthorizer)?.AuthorizeRequest(message);
                return httpClient.SendAsync(message, option, token)
#if NET_3_5
                .ContinueWith(t =>
                {
                    Interlocked.Decrement(ref _connectionCount);
                    return t.Result;
                })
#endif
                ;
#if !NET_3_5
            })?.Unwrap()?.ContinueWith(t =>
            {
                message.Dispose();
                _sendSemaphore?.Release();
                if(t.IsFaulted) {
                    var e = t.Exception;
                    if(Misc.UnwrapAggregate(e) is ObjectDisposedException) {
                        return null;
                    }

                    throw e;
                }

                return t.Result;
            });
#endif
        }