Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the garbage collection of Dotnet

2025-04-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to understand the garbage collection of Dotnet". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Before talking about garbage collection, let's talk about two concepts:

Managed code, which is managed by CLR

Unmanaged code, which is directly executed by the operating system

In the early days of C++, memory allocation and release were handled manually, but in the common language progressive CLR, there was a garbage collector GC to act as an automatic memory manager to do the same thing. From then on, for developers, we don't need explicit code to perform memory management. The benefits of this are obvious: a large number of memory-related errors are eliminated, such as memory leaks caused by not releasing objects, or attempts to access the memory of objects that have been freed, and so on.

I. recovery and management of managed resources

As mentioned above, the garbage collection GC is an automatic memory manager in Dotnet, a mechanism for cleaning and recycling unreferenced parts of heap memory.

Typically, CLR initiates garbage collection in these situations:

When memory needs to be allocated to a new object on the heap, but there is not enough free memory

When an object is forced to Dispose

The memory of the allocated objects on the managed heap exceeds the threshold (this threshold is dynamically adjusted)

The GC.Collect method was called

These contents are the foundation, understand is very good, have something to say during the interview. It doesn't matter if you don't understand, it won't affect making a good program.

The following, if you can remember, is very helpful for program development.

In Dotnet's garbage collection mechanism, the collector optimizes itself and is suitable for a variety of scenarios. However, we can still set the type of garbage collection according to the running environment.

Dotnet's CLR provides the following two types of garbage collection:

Workstation garbage collection

Server garbage collection

There are some differences between the two recycling mechanisms.

Workstation recycling, which is mainly designed for client applications, is also the default recycling mechanism of the program. The garbage collection process runs on the user thread that triggers the garbage collection and uses the same priority. In this way, the advantage is that it will not be suspended or delayed, and the disadvantage is that it needs to compete with other threads for CPU time. When there is only one CPU in the running environment, the system will automatically use the workstation mode, no matter what you set it to.

Server recycling is aimed at high-throughput server applications. The recycling process runs on dedicated high-priority threads, and multi-threads are running by default, so it is more efficient, but the disadvantage is that it takes up more resources. and due to interference between threads and context switching, it will affect the overall performance.

Therefore, what kind of recycling mechanism to choose needs to be carefully analyzed. Usually for common applications, workstation recycling is fine. If it is a server-side API service, you need to select server recycling. If you need to start multiple instances on the server side for processing, such as saving the data of the bus, it is better for the workstation to recycle.

Set garbage collection method. When developing, you can add the following to the xxx.csproj file:

True

Among them, setting true is the server mode, setting false is the workstation mode, and of course, if you remove this line, the default is also workstation mode.

For applications that are already online in the production environment, the recycling mode can also be modified. Find the xxx.runtimeconfig.json file in the program directory and add:

"configProperties": {"System.GC.Server": true}

The relationship between the two configurations is that if ServerGarbageCollection is added to .csproj during development, System.GC.Server is automatically added to .runtimeconfig.json at release time.

II. Recovery and management of unmanaged resources

The recycling mechanism mentioned above is aimed at managed resources.

For unmanaged resources, GC does not actively recycle them. To recycle unmanaged resources, you can only write code by hand and explicitly release.

Generally speaking, the resource files, network or database connections of the operating system used in the program are unmanaged resources and need to be cleaned manually.

There are two ways to clean up non-trust managed resources:

Use the Terminator Finalize and be recycled by GC

Manual processing of Dispose

2.1 use Terminator Finalize

The finalizer Finalize is a virtual method of System.Object, which is called by garbage collection before GC reclaims the memory of the object. We can override this method to release unmanaged resources.

Say a few more words: it seems that MS is a little hesitant about this part, so the rules here are always in the middle. C # is not strict in its support for destructors. System.Object supports rewriting Object.Finalize methods, but the classes it creates do not. Rewriting can only be achieved by rewriting destructors, and the compiler wraps the code in destructors or rewritten Finalize in try blocks, and finally calls Object.Finalize to implement it.

The disadvantage of using Terminator is also obvious. When GC detects that an object needs to be reclaimed, it calls the finalizer after an uncertain period of time. This uncertainty is annoying, and it's hard to predict when the object will actually be released.

Although Finalize seems to clean up unmanaged resources manually, it is actually done by the garbage collector. Its greatest role is to ensure that unmanaged resources must be released.

2.2 handle Dispose manually

The most important reason for manual processing is to release it immediately when needed, rather than letting the garbage collector release after an indefinite delay.

Manual release, the main task is to provide an implementation of IDisposable.Dispose to achieve the deterministic release of unmanaged resources. In this way, when you call the Dispose method when you need to release, the unmanaged resource is immediately released.

Manual processing is easy to implement. The framework provides an interface System.IDisposable:

Public interface IDisposable {void Dispose ();}

It contains only one method, Dispose. When using, you need to implement this method to release unmanaged resources in a timely manner after the use is complete.

At the same time, the Dispose method provides a GC.SuppressFinalize method to tell GC that the object has been processed manually and that you no longer need to call the finalizer.

Public void Dispose () {GC.SuppressFinalize (this);}

In this way, the memory of the object can be reclaimed in advance.

In some cases, the IDisposable.Dispose method may not be called to release unmanaged resources, but deterministic release is required in the scenario, which may be achieved by rewriting Object.Finalize:

Public class MyClass {~ MyClass () {/ / TODO: release unmanaged resources}}

It's a little strange, isn't it?

In fact, this is where I said MS hesitated. If you rewrite Object.Finalize directly, it looks like this:

Public class MyClass {protected override void Finalize () {/ / TODO: release unmanaged resources}}

An error Do not override object.Finalize is reported when compiling. Instead, provide a destructor., and his correct way of writing is a destructor.

The content mentioned above, made into a routine template, will look like this:

Public class MyClass: IDisposable {private bool disposedValue Protected virtual void Dispose (bool disposing) {if (! disposedValue) {if (disposing) {/ / TODO: release managed state (managed objects)} / / TODO: release unmanaged resources (unmanaged objects) and replace finalizers / / TODO: set the large field to null disposedValue = true }} ~ MyClass () {Dispose (disposing: false);} public void Dispose () {Dispose (disposing: true); GC.SuppressFinalize (this);}}

If you see here, it is recommended to save the above routine template. This is the most complete version, and most of what can be found online is a simplified version.

In fact, many of the classes we often use implement the IDisposable interface. For example, any class that can be called with using implements the IDisposable interface. There are other classes that change Dispose to a different name, such as the Close method in IO, which is a Dispose.

In addition, if the object implements the IDisposable interface and we new the object directly, then we need the Dispose object at the end of the use. Because now that the designer has chosen Dispose, it is right to call Dispose at the end.

III. Summary

Finally, make a simple summary.

Garbage collection mode choice: the application can allocate less resources, or can compete for fewer resources, use workstation mode, otherwise use server mode.

In terms of recycling, managed resources are thrown to GC for automatic processing, while unmanaged resources need to be processed manually:

Where:

Finalize marks that unmanaged resources can be recycled, and then GC performs the recycling work.

Dispose is called directly and recycled immediately.

This is the end of "how to understand Dotnet garbage collection". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report