3.37Adding Resources to Release When the Request Ends

Created on Aug 17, 2026~2 min read

Memory safety is an issue every developer must take seriously. When sending an HTTP request, you sometimes need to introduce unmanaged resources — for example, when sending a file, you need to read the file from disk and send it as a stream. In such cases, if handled improperly, you may encounter the problem of the stream resource not being released.

To solve this problem, we can add resources that are automatically processed for release after the request ends:

cs
// Open the file and read the file stream (without using)var fileStream = File.OpenRead(@"C:\Workspaces\httptest.jpg");var httpRequestBuilder = HttpRequestBuilder.Post("https://furion.net/")    .SetContent(fileStream);  // Set the request content    .AddDisposable(fileStream) // Add a resource to release when the request ends    .AddDisposables(fileStream1, fileStream2); // Supports adding resources in bulk// Send the requestvar responseMessage = await httpRemoteService.SendAsync(httpRequestBuilder);// At this point, fileStream, fileStream1, and fileStream2 have been released automatically. ✅

The AddDisposable method accepts any object that implements the IDisposable interface as an argument, and it can be called repeatedly; each call adds a new IDisposable object to the collection.