I'm having a OutOfMemoryException exception.

Source: Internet
Author: User
Tags httpcontext server memory

I encountered an OutOfMemoryException exception 2008-11-28 09:52

The after-Sales service system of ASP has been running for nearly 1 years, and yesterday, when the data was exported in the year, OutOfMemoryException anomaly occurred, and the data volume was about 50M. 50M should not be very large, put in the database is also tens of thousands of (a lot of table fields). The settings for the IIS6 application pool are default. Do not know why this, the time of the native test is not the problem. The reason for estimating the problem is: 1. Memory control problem in the program; 2. Problems with server memory reclamation. It is said that IIS6 can use up to 800M of memory, and outofmemoryexception errors may occur if IIS sets more than 800M of memory. IIS settings are also important to set up memory recycling in the morning and to set the cycle of memory recycling to 600 minutes.

In the program must pay attention to control the memory, although the C # program is basically managed, by the garbage collector to collect memory, but we must pay attention to the use of multiple, data read with DataReader. Do not use datasets to deal with large amounts of data, and make reasonable use of paging. Look at the system code, there are many places need to optimize, alas, not so much time to engage, depressed. You should pay more attention to writing programs later.

For this anomaly, there seems to be no good solution, just write the program when more attention. The cure can only be operated on the procedure. This exception can be caught in Application_Error.

Examples of handling anomalies in ================application_error

Initialize exception
Exception objexp = HttpContext.Current.Server.GetLastError ();

Ignore an Internet express or other network tool to download exceptions caused by bookmarked HTTP requests]
if (HttpContext.Current.Request.Url.ToString (). IndexOf ("#")! =-1)
{
Clears all errors for the current HTTP request
HttpContext.Current.ClearError ();

Output
HttpContext.Current.Response.Write ("Your request is illegal and will be ignored by the system");
Return
Return
}

Looping through exception events
for (Exception tempexception = objexp; Tempexception! = NULL; Tempexception = tempexception.innerexception)
{
If the system detects illegal characters, it prompts and returns
if (Tempexception.gettype (). ToString () = = "System.Web.HttpRequestValidationException")
{
Clears all errors for the current HTTP request
HttpContext.Current.ClearError ();

Output
HttpContext.Current.Response.Write ("The system has detected that you have entered an illegal character");

Return
Return
}

               //exception is memory overflow
                if ( Tempexception.gettype (). ToString () = = "System.OutOfMemoryException")
                 {
                    //Clears all errors for the current HTTP request
                     HttpContext.Current.ClearError ();

Output
HttpContext.Current.Response.Write ("System is being maintained ...");
HttpContext.Current.Response.Write ("Server resource exhausted, please try again later!") ");
Return
Break
}

The exception that is thrown by a warning or error returned by SQL Server
if (Tempexception.gettype (). ToString () = = "System.Data.SqlClient.SqlException")
{
byte Errlevel = ((System.Data.SqlClient.SqlException) tempexception). Class;
int number = ((System.Data.SqlClient.SqlException) tempexception). number;

severity processing [Database server has been closed]
Number = = [SQL Server does not exist or access is denied]
Number = = 11 [General network error. Please check your network documentation]
if (Errlevel = = && (number = = 17 | | Number = = 11))
{
Clears all errors for the current HTTP request
HttpContext.Current.ClearError ();

Output
HttpContext.Current.Response.Write ("System is being maintained ...");
HttpContext.Current.Response.Write ("The database server is down, please try again later!") ");

                        //Return to
                         return;
                    }

                    //severity processing [database server is shutting down]
                    //number = = 6002 [SHUTDOWN is in progress. Please sign out]
                     if (errlevel = = && Number = = 6002)
         & nbsp;          {
                        // Clears all errors for the current HTTP request
                         HttpContext.Current.ClearError ();

Output
HttpContext.Current.Response.Write ("System is being maintained ...");
HttpContext.Current.Response.Write ("The database server is shutting down, please try again later!") ");

Return
Return
}

                    //severity handling [System is logging into database server]
                    //number = = 6005 [SHUTDOWN in progress, user logon failed. Currently only administrators can connect]
                     else if (errlevel = = && Number = = 6005)
                     {
                         //Clears all errors for the current HTTP request
                         HttpContext.Current.ClearError ();

                        //Output
                         HttpContext.Current.Response.Write (" System maintenance ... ");
                         HttpContext.Current.Response.Write ("The system is logging into the database server, please try again!") ");

                        //Return to
                         return;
                    }
               }

               //Event handling
                if ( Tempexception.message = = "Timeout time has arrived. The timeout period has expired before getting a connection from the pool. This may occur because all pooled connections have been used and the maximum pool size has been reached. ")
                {
                    // Clears all errors for the current HTTP request
                     HttpContext.Current.ClearError ();

Output
HttpContext.Current.Response.Write ("System maintenance ...");
HttpContext.Current.Response.Write ("The database server is busy, please try again later!") ");

Return
Return
}

               //Ignore frame exceptions
                if ( Tempexception.gettype (). ToString () = = "System.Web.HttpUnhandledException")
                 {
                    //Return to
                     return;
               }

Write exception
Omit program .....
));

Asp. The processing scheme of OutOfMemoryException exception in net

I believe that people who do large Web applications in ASP have encountered OutOfMemoryException this anomaly, I have studied this problem for a long time, in Microsoft's technical documentation also understand the cause of this problem, to be honest, I still do not have the perfect solution, here is just my experience in dealing with this issue Come out and share with everyone and avoid the problem as much as possible.

1) First, on the hardware configuration, the cause of this problem I think a lot of people already know, that is, IIS for memory management There are some limitations, the general understanding is the 800M thread memory usage limit (through some of my customer practice proves that this is true, even lower ...), Whether it's w3wp or aspnet_wp, this limitation is significant for the machine configuration of the ASP. More than 2G of memory is very small for a simple Web server, so the number of CPUs can be considered in terms of the configuration of the Web server.

2) IIS configuration on the scenario, IIS5.0 can install a iis5recycle program that uses the form of a service to recycle worker processes, installation instructions: http://support.microsoft.com/?id= 322350, for IIS6.0 you can set the auto-recycle worker thread's time on the application pool configuration, I will usually set at 2 o'clock in the morning:)

3) on the. NET Framework configuration, modify the configuration section in the Machine.config configuration file <processModel> the property "MemoryLimit", the value of this property defaults to "60", is a percent data, We need to set this value according to the actual amount of memory on the server and then the 800M limit, so IIS automatically recycles the process when this threshold is reached.

4) in the development of Web applications, it is necessary to minimize the use of memory waste, and release resources in a timely manner, I would like to illustrate 3 points: 1, the code actively call the Dispose method for resource release, 2, for the entity class as far as possible reuse, do not make redundant declarations and create, 3, Reduce session usage and shorten the duration of the session, especially for big data objects as far as possible in the session

5) A more general approach, in the base class of the Web application through try{}catch{} to actively catch the OutOfMemoryException exception, found that the exception is directly called Gc.collect () for forced garbage collection.

Finally, a lot of friends mentioned that the 32-bit system can open 3G mode for large memory use, this itself is not a problem, but based on personal experience, its simple Web application is not very helpful, if the Web server is also recommended for the use of this mode.

I hope you will be helpful in dealing with this problem.

===========

Asp. NET in the OutOfMemoryException
In the blog Park saw a friend wrote the article "How to deal with OutOfMemoryException anomalies?" , so I want to communicate with you about the problem of outofmemoryexception in ASP.
In fact, on an ASP. NET Web server, ASP. NET can use the memory, usually not equal to all the amount of memory. In the Machine.config configuration file, configuration section <processModel> has a property "MemoryLimit", the value of this property is a percent, the default is "60", That is, you specify an ASP. (in Task Manager, you can see that the process of ASP. IIS5 in ASPNET_WP,IIS6 is w3wp) can use 60% of all physical memory. When the amount of memory that ASP. NET uses exceeds this limit, IIS starts the Auto-recycle (recycle) process, which is to create a new process to handle the HTTP request and reclaim the memory consumed by the old process.
When we have a very large memory server, the value of "memorylimit" needs to be adjusted appropriately. For example, we have a 4G memory server, then 4gx60%=2.4g. However, for the WIN32 operating system, only 2 g of all memory space a process can occupy. When the amount of memory that the ASP. NET process consumes starts to reach 2G, because it does not reach the 2.4G recycle threshold, IIS does not start the recycle process operation, but because of the Win32 limit, the process cannot actually allocate more memory, so OutOfMemoryException is likely to be thrown out. In order to avoid this, we have to make the "memorylimit" appropriately smaller so that IIS can recycle the process earlier.
Microsoft recommends that the ASP. NET process consumes no more than 60% of the memory, and it is best to make the calculated actual value no more than 800M. That is, for a server with 4G of memory, it is best to set the "MemoryLimit" property to "20". Setting an appropriate recycling threshold to allow IIS to process recycling in a timely manner is important to ensure stable operation of the entire server and avoid outofmemoryexception.
In IIS6, ASP. NET process is no longer determined by the "memorylimit" property in the configuration section, but is determined by the settings in the application pool configuration in IIS Manager.
However, even if these configurations are set up correctly, there is no guarantee that outofmemoryexception will be completely avoided, for reasons such as multiple and complex, such as a memory recovery operation may take too much time, and so on. Developers need to be aware of the code to keep in mind not to use and waste memory unnecessarily. :)

I'm having a OutOfMemoryException exception.

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.