Dispose
andFinalize
It 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.
becauseFinalize
The uncertainty and the cost in terms of performance are high, soDispose
Methods are used much more frequently thanFinalize
。 In fact, we can achieve it in oneIDisposable
Used on the type of interfaceDispose
method.
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 articleDispose
Usage of.
1. Create a class that implements IDisposable interface
We will now create an implementationIDisposable
The 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();
}
}
}
FileManager
Class implementationIDisposable
Interface and contains two methods:Write
andDispose
。 The former is used to write text to a file asynchronously, and the latter is used to callFileStream
ClassDispose
Method to delete from memoryFileStream
example.
Next, we introduce in ASP Net core 6IDisposable
Object.
2. Use the “using” statement to handle IDisposable objects
handleIDisposable
The simplest way to an instance is to use the “using” statement, which automatically calls theDispose
method. 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.RegisterForDispose
Method can be used to register in this wayIDisposable
Object for processing. It accepts implementationIDisposable
Interface, and ensure that it is passed as a parameterIDisposable
Object is processed automatically with each request.
The following code demonstrates how to useHttpResponse.RegisterForDispose
Method is registered at the end of each HTTP requestFileManager
Class.
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 processingIDisposable
Object by using ASP Net core. You can useTransient
、Scoped
orSingleton
Instance to create services and add them to the built-in IOC container.
takeIDisposable
Object added toStartup
ClassConfigureServices
Method so that these objects are automatically processed with each HTTP request.
5. Use ihostapplicationlife event to handle idependency object
ASP. Net core has a nameIHostApplicationLifetime
Interface that allows you to run custom code when the application starts or closes. You can take advantage of the of this interfaceRegister
Method to register events.
Startup
ClassConfigure
The following parameters are acceptable:
- IApplicationBuilder
- IHostingEnvironment
- ILoggerFactory
- IHostApplicationLifetime
The following code demonstrates how to useIHostApplicationLifetime
Interface 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
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.