question

Stesvis-5434 avatar image
0 Votes"
Stesvis-5434 asked Bruce-SqlWork answered

Cannot access a closed stream

I am noticing lots of httpclient errors in my app.
This one says: System.ObjectDisposedException: Cannot access a closed Stream


// App.xaml.cs
private static HttpClient _myHttpClient;
public static HttpClient MyHttpClient
{
    get
    {
        if (_myHttpClient == null)
        {
            _myHttpClient = new HttpClient()
            {
                Timeout = TimeSpan.FromSeconds(120),
                BaseAddress = new Uri(ApiUrlsBase.BaseUrl),
            };

            _myHttpClient.DefaultRequestHeaders.Add(CustomRequestHeaders.ApiVersion, "2");
        }

        return _myHttpClient;
    }
}

// HttpService.cs
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

var payload = JsonConvert.SerializeObject(postData, Formatting.Indented);
var postContent = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await MyHttpClient.PostAsync(url, postContent); // this line threw the exception


Of course this only happens sometimes, very randomly.
What could it be? Any way to track it down or prevent it?

dotnet-csharpdotnet-xamarin
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi, Stesvis-5434. Do you dispose the httpclient? If so, please don't do that. HttpClient is designed to be reused and handle multiple simultaneous requests.
Here is a similar issue case which may help you get the cause, please check: https://stackoverflow.com/a/50991598/11083277

0 Votes 0 ·

I don't, i use it as singleton.

0 Votes 0 ·

Did you check the Stack Trace of the exceptions?


0 Votes 0 ·

Yes, the line throwing the exception is the _myHttpClient.PostAsync

0 Votes 0 ·

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

You may need to check the logs on the server you are calling.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.