How to ensure disposal of an IDisposable returned anonymously into a consuming method?

Viewed 52

I'm creating an instance of HttpRequestMessage and return it to be used through the HTTP client.

HttpClient Client { get; init }
HttpRequestMessage GenerateRequest() { ... }     

Then, I'm using Polly to execute the call under a policy with a couple of iterations and exponential delay in between.

using HttpResponseMessage response = await RetryPolicy
  .ExecuteAsync(() => Client.SendAsync(GenerateReqest()));

Since HttpRequestMessage implements IDisposable, I've been recommended to ensure invocation of Dispose() as the object goes out of scope, like this:

using HttpResponseMessage response = await RetryPolicy
  .ExecuteAsync(() => 
  {
    using HttpRequestMessage request = GenerateRequest();
    Client.SendAsync(request);
  });

Is there a simpler syntax to achieve that? I could call the disposer explicitly but that doesn't change the fact that I still would have to wrap it in a body instead of going simple lambda expression, which I'd prefer.

I went through the HttpRequestMessage class and it's Dispose() as well as the underlying HttpContext and so on. As far I can see, there's no actual registration in an event or such that requires the disposability, so I guess it's there in case something extra unusual happens. So I'm considering skipping the using var name = ... syntax and let the GC deal with it eventually.

One way or the other, I'd like to have only lambda expression and if it's possible, I can apply disposer too, though, under the condition that it won't require me to create a multi-statement.

1 Answers

Depending what your GenerateRequest does, you most probably don't need to call the Dispose explicitly. There is a github issue which details when to call the Dispose on the HttpRequestMessage and HttpResponseMessage. Let me quote here the relevant part:

It's not important in these scenarios. Disposing a request or response only calls Dispose on their Content field. Of the various HttpContent implementations, only StreamContent needs to dispose anything. HttpClient's default SendAsync fully buffers the response content and disposes the stream, so there's nothing the caller needs to do.

So, if your GenerateRequest does not use StreamContent then don't bother to Dispose it by yourself.

Related