ASP. Net , four methods of using , dispose , to release resources are introduced in detail


ASP. Net using dispose to release resources

Dispose and finalize are run Net and Net core applications are two ways to free up the occupied resources. In general, if there are unmanaged resources in the application, the resources occupied by these resources should be explicitly released.

Because of the uncertainty of finalize and the high cost of performance, the disposal method is used much more frequently than finalize. In fact, we can use the dispose method on a type that implements the IDisposable interface.

The code examples provided in this article all run in Visual Studio 2022 by default.

Using vs2022 to create ASP Net core project

We created an in Visual Studio 2022 Net core project. Follow these steps to create a new in Visual Studio 2022 Net core web API 6 project.

1) Start the visual studio 2022 ide. 2) Click create new project.

3) In the create new project window, select core web API from the list of templates displayed.

4) Click next.

5) In the configure your new project window, specify the name and location of the new project.

6) According to your preference, you can select the “place solution and project in the same directory” check box.

7) Click next.

8) In the “additional information” window displayed next, select from the drop-down list at the top Net 6.0 as the target framework. Leave authentication type as none (default). Make sure use controllers Options.

9) Make sure the “enable docker”, “configure for HTTPS” and “enable open API support” check boxes are not selected, as we will not use any of these features here. You can also choose to uncheck the “use controllers” check box because we will create our own controllers.

10) Click create. This will create a new in Visual Studio 2022 Net core 6 web API project. We’ll use this project in a later part of this article to illustrate the use of dispose.

1. Create a class that implements IDisposable interface

We will now create a class that implements the IDisposable interface. The code is as follows:

public class FileManager: IDisposable {
    FileStream fileStream = new FileStream(@"C:\Test.txt",
    public async Task Write(string text) {
            byte[] buffer = Encoding.Unicode.GetBytes(text);
            int offset = 0;
            try {
                await fileStream.WriteAsync(buffer, offset,
            catch {
                //Write code here to handle exceptions.
    public void Dispose() {
            if (fileStream != null) {

The FileManager class implements the IDisposable interface and contains two methods: write and dispose. The former is used to write text to a file asynchronously, and the latter is used to delete a FileStream instance from memory by calling the dispose method of the FileStream class.

Next, we introduce in ASP Net core 6 has four methods to deal with IDisposable objects.

2. Use the “using” statement to handle IDisposable objects

The easiest way to handle IDisposable instances is to use the “using” statement, which automatically calls the dispose method on the instance. The following code snippet illustrates this.

using(FileManager fileManager = new FileManager())
        await fileManager.Write("This is a text");

3. Handle IDisposable objects at the end of the request

In ASP Net core or ASP When working in net core MVC applications, we may often need to process objects at the end of HTTP requests.

HttpResponse. The registerfordispose method can be used to register IDisposable objects in this way for processing. It accepts an instance of a class that implements the IDisposable interface and ensures that the IDisposable object passed to it as a parameter is processed automatically with each request.

The following code demonstrates how to use httpresponse The registerfordispose method registers an instance of the FileManager class at the end of each HTTP request.

public class DefaultController: ControllerBase {
    readonly IDisposable _disposable;
    public DefaultController() {
            _disposable = new FileManager();

4. Use the built-in IOC container to handle IDisposable objects

Another way to automatically handle IDisposable objects is to use ASP Net core. You can use transient, scoped, or singleton instances to create services and add them to the built-in IOC container.

Add IDisposable objects to the IOC container in the configureservices method of the startup class so that these objects are processed automatically with each HTTP request.

5. Use ihostapplicationlife event to handle idependency object

ASP. Net core has an interface called ihostapplicationlife, which allows you to run custom code when an application starts or closes. You can use the register method of this interface to register events.

The configure method of startup class can accept the following parameters:

  1. IApplicationBuilder
  2. IHostingEnvironment
  3. ILoggerFactory
  4. IHostApplicationLifetime

The following code demonstrates how to use the ihostapplicationlife interface to register objects for disposal when the application closes.

public void Configure(IApplicationBuilder app, IHostApplicationLifetime hostApplicationLifetime) {
private void OnShutdown() {
    //Release the code of the object

Finally, ASP Net core 6 does not create startup by default cs。 We need to create one manually and then in program Write the following code in the. CS file to specify the startup class application you will use in it.

var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureWebHostDefaults(webBuilder =>
using var app = builder.Build();

Unlike finalize, we explicitly use the dispose method to release unmanaged resources. You should explicitly call the dispose method on any object that implements it to release any unmanaged resources that the object may hold its references.

reference material:

1. C# tutorial

2.Programming treasure house

Recommended Today

What is the experience of developing a grey wolf game from scratch?

Geek Jiangnan: a programmer who is particularly dedicated to development technology, has unique insights and in-depth research on mobile development, has many years of experience in IOS, Android and HTML5 development, and has unique insights and in-depth research on the development of nativeapp, hybridapp and webapp. In addition, he is also proficient in JavaScript, angularjs, […]