C # Windows service program memory leakage

Source: Internet
Author: User

Recently, I made a serviceProgramFor telecom projects, it is necessary to ensure 7x18 hours of operation (from to), adopt event-driven, result, program run for 15 days, memory occupied 1 GB, to solve the memory leakage problemArticle.....

There are many causes for Memory leakage. Therefore, there are different solutions for different situations.

First, let's talk about the possible causes of Memory leakage in this project.

1: multithreading, reading of resource variables, and endless loops (this program does not have an endless loop ..)

2: The resources are not completely released. Of course, this program is driven by events. The reason may be that the events are not correctly released...

 

For the first type: events are not correctly released. What does it mean?

For example:Code

 

Code
Public   Class Eventtest1: idisposable
{
Private   Int [] Testarr =   New   Int [ 100000000 ];

Public   Event Testdelegate =   Null ;

Protected   Void Ontest ()
{
If (Testdelegate ! =   Null )
{
Testdelegate ();
}
}

Public   Void Add ()
{
Systemevents. displaysettingschanged+ =Systemevents_displaysettingschanged;
Ontest ();
}

Void Systemevents_displaysettingschanged ( Object Sender, eventargs E)
{

}

Idisposable Member # Region Idisposable Member

Public   Void Dispose ()
{
Systemevents. displaysettingschanged-=Systemevents_displaysettingschanged;
}

# Endregion
}

 

Unless you display the proxy dispose method, memory leakage will definitely occur...

 

Therefore, three methods are considered to solve Memory leakage:

1: Write another service program to shut down and restart the service program with Memory leakage on a regular basis every day.

Feasibility:

(1): This is the simplest and most likely way to achieve results. Why is it the most likely result? The reason is that if you use a service program to restart or close a service program, it may take too short time to close and start the service program. The subsequent service programs will show the memory usage, there are still so many .... The reason for this is still being studied...

(2): although this is the easiest way, it is the least recommended method. Besides, even if the problem is solved, you cannot gain much experience or improve your abilities.

(3): Do not use this method unless your customer asks you to immediately solve the memory leakage problem.

2: the most authentic and most consistent with the development and design ideas,Refactor the code to release the resources to be released in time

Feasibility:

(1) Time Problem: When memory leakage occurs, the customer certainly hopes to get confirmation from the development team as soon as possible that the problem has been resolved. Obviously, restructuring a program, you can clear all the code again, which is obviously not completed in a moment.

Solution:

(1): Let's talk about the dispose mode here (I don't know if there is any such mode, as if I haven't seen it in Java and design patterns ..).

In the dispose mode, the code is simple, but the method is absolutely classic.

Idisposable
Release resources to implement idisposable # Region Release resources to implement idisposable

Bool Misdisposed =   False ;

Public   Void Dispose ()
{
Dispose (True);
GC. suppressfinalize (This);
}

Protected   Void Dispose ( Bool Disposing)
{
If ( ! Misdisposed)
{
If (Disposing)
{
Disposeoverride (True);
}
Disposeoverride ( False );
Misdisposed =   True ;
}
}

Protected   Virtual   Void Disposeoverride ( Bool P)
{
If (P)
{
//Release managed resources
}
Else
{
//Release unmanaged Resources
}
}
# Endregion

Destructor:
  This . Dispose ( False );

 

Of course, if all the resources in your program to be released are released and memory leaks exist, then... I can't ....

 

3: Use the application domain

If you reference the official website, let us know:

  • Use the application domain to isolate tasks that may terminate processes. IfAppdomainCan be detached if the status becomes unstable.AppdomainBut does not affect the process. This is important when the process has to run for a long time without being restarted. You can also use application domains to isolate tasks that do not share data.

  • If the Assembly is loaded into the default application domain, the Assembly cannot be detached from the memory when the process is running. However, if you open another application domain to load and execute an assembly, the application domain will be uninstalled at the same time. Use this technique to minimize the working sets of long-running processes that occasionally use large DLL.

  • The last sentence is enough ..

    I used appdomain for the first time. Therefore, I can only provide the Code:

    1: first, encapsulate all business code in one class.

    2: open a new appdomain.

    Appdomain
    Type testtype = Type. GetType ( " Boco. Hubei. Huangshi. alarmlocation. server. btsalarmlocationservice " );
    Assembly ass = Testtype. assembly;
    String Exeassembly = Ass. fullname;

    Appdomainsetup ads =   New Appdomainsetup ();
    Ads. applicationbase =
    Appdomain. currentdomain. basedirectory;
    Ads. disallowbindingredirects =   False ;
    Ads. disallowcodedownload =   True ;
    Ads. configurationfile =
    Appdomain. currentdomain. setupinformation. configurationfile;

    Usercreateappdomain = Appdomain. createdomain ( " Boco.hubei.huangshi.alarmlocation.server.exe " , Null , ADS ); // Bytes
    Objecthandle = Usercreateappdomain. createinstance (exeassembly, " Boco. Hubei. Huangshi. alarmlocation. server. btsalarmlocationservice " );
    Btsalarmlocationservice = (Btsalarmlocationservice) objecthandle. Unwrap ();

     

    For method 1 and 3, it is only a temporary cure, but only 3rd to 1st, a little more advanced ....

    In this article, all the code and so on provide only one idea. You have the final say about how to operate the program...

    Of course, for the National Day to be able to feel at ease, this program will only use 3rd methods. Moreover, the unused methods, of course, should be used.

     

    Finally, let's talk about the cause of Memory leakage in the program but it cannot be solved:

    1: Customer reasons

    The functions implemented by this program are for the first time in the local team. Therefore, Bureau staff hope to quickly deliver results and report to the leadership to increase their performance.

    2: Company reasons

    (1) When the project manager knows that the program has not been fully tested, he also urges the development team to provide the program to run the test online. As a result, after the program is launched, any small modification of the program is made, it can be implemented only after being signed and confirmed by the Bureau's leaders. Moreover, during the Olympics, a signing process may take too much time...

    (2) The project manager did not realize the impact of the system on the Performance of Bureau staff. If the program encounters a ding problem on a certain day, the team's staff on that day will be thundered...

    3: Reasons for the development team

    Of course, this is the most important thing.

    (1) the development team lead does not have a strong attitude to control the project manager's failure to pass the program.

    (2) there are still some problems with the coding capability of the development team members and the overall consideration of the system.

    This is just a simple solution to the current problem.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.