ASP. Net uses dispose to release resource instances in vs2022

Time:2022-5-19

DisposeandFinalizeIt works 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.

becauseFinalizeThe uncertainty and the cost in terms of performance are high, soDisposeMethods are used much more frequently thanFinalize。 In fact, we can achieve it in oneIDisposableUsed on the type of interfaceDisposemethod.

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 asp.net in Visual Studio 2022 Net core project. Follow these steps to create a new asp.net in Visual Studio 2022 Net core web API 6 project.

  • 1) Launch visual studio 2022 ide.
  • 2) Click create new project.
  • 3) In the create new project window, select asp.net 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 asp.net in Visual Studio 2022 Net core 6 web API project. We’ll use this project to illustrate it in later parts of this articleDisposeUsage of.

1. Create a class that implements IDisposable interface

We will now create an implementationIDisposableThe class code of the interface is as follows:


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

FileManagerClass implementationIDisposableInterface and contains two methods:WriteandDispose。 The former is used to write text to a file asynchronously, and the latter is used to callFileStreamClassDisposeMethod to delete from memoryFileStreamexample.

Next, we introduce in ASP Net core 6IDisposableObject.

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

handleIDisposableThe simplest way to an instance is to use the “using” statement, which automatically calls theDisposemethod. 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.RegisterForDisposeMethod can be used to register in this wayIDisposableObject for processing. It accepts implementationIDisposableInterface, and ensure that it is passed as a parameterIDisposableObject is processed automatically with each request.

The following code demonstrates how to useHttpResponse.RegisterForDisposeMethod is registered at the end of each HTTP requestFileManagerClass.


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

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

Another automatic processingIDisposableObject by using ASP Net core. You can useTransientScopedorSingletonInstance to create services and add them to the built-in IOC container.

takeIDisposableObject added toStartupClassConfigureServicesMethod so that these objects are automatically processed with each HTTP request.

5. Use ihostapplicationlife event to handle idependency object

ASP. Net core has a nameIHostApplicationLifetimeInterface that allows you to run custom code when the application starts or closes. You can take advantage of the of this interfaceRegisterMethod to register events.

StartupClassConfigureThe following parameters are acceptable:

  • IApplicationBuilder
  • IHostingEnvironment
  • ILoggerFactory
  • IHostApplicationLifetime

The following code demonstrates how to useIHostApplicationLifetimeInterface registers objects for disposal when the application closes.

public void Configure(IApplicationBuilder app, IHostApplicationLifetime hostApplicationLifetime) {
    hostApplicationLifetime.ApplicationStopping.Register(OnShutdown);
}
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 =>
{
    webBuilder.UseStartup<Startup>();
});
using var app = builder.Build();
app.Run();

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

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.