System.Net.Http.HttpClient.Dispose C# (CSharp) Method

Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
        protected override void Dispose(bool disposing)
        {
            if (disposing && !_disposed)
            {
                _disposed = true;

                // Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
                // the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
                // a new CTS. We don't want a new CTS in this case.
                _pendingRequestsCts.Cancel();
                _pendingRequestsCts.Dispose();
            }

            base.Dispose(disposing);
        }

Usage Example

        public override bool Execute()
        {
            HttpClient client = null;
            try {
                var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
                var mediaType = new MediaTypeHeaderValue("application/json");
                var jsonSerializerSettings = new JsonSerializerSettings();
                var requestMessage = new HttpRequestMessage<string>(
                    this.PostContent,
                    mediaType,
                    new MediaTypeFormatter[] { jsonFormatter });

                client = new HttpClient();
                HttpResponseMessage response = null;
                System.Threading.Tasks.Task postTask = client.PostAsync(this.Url, requestMessage.Content).ContinueWith(respMessage => {
                    response = respMessage.Result;
                });

                System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { postTask });

                response.EnsureSuccessStatusCode();

                return true;
            }
            catch (Exception ex) {
                string message = "Unable to post the message.";
                throw new LoggerException(message,ex);
            }
            finally {
                if (client != null) {
                    client.Dispose();
                    client = null;
                }
            }
        }
All Usage Examples Of System.Net.Http.HttpClient::Dispose