Request timed out frequently
Asked Answered
G

4

5

I face the following problem time after time and i don't know how to fix it ..

I get the following errors frequently , and i had to restart the IIS or republish to fix the problem temporary :

Error Message:Request timed out.
Error Message:ERROR [08S01] [Informix .NET provider]Communication link failure.
Error Message:Thread was being aborted.

I try to make :

<httpRuntime executionTimeout="600" />

but still the same problems !!


Stack Trace:
   at System.Web.HttpContext.InvokeCancellableCallback(WaitCallback callback, Object state)
   at System.Web.UI.Page.AsyncPageBeginProcessRequest(HttpContext context, AsyncCallback callback, Object extraData)
   at ASP.appmaster_aspx.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object data)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

My PageLoad :

 protected void Page_Load(object sender, EventArgs e)
        {


            if (Session["emp_num"] != null && !string.IsNullOrEmpty(Session["emp_num"].ToString()))
            {
                try
                {

                    string user_setting = Personalization_DAL.CheckWidgetSettings(int.Parse(Session["emp_num"].ToString()));

                    if (!string.IsNullOrEmpty(user_setting))
                    {
                        user_flag = int.Parse(user_setting);
                    }

                    GetLinkedApp = DB_Connection_s.DB_Connection.GetLinkedAppUser(int.Parse(Session["emp_num"].ToString()));
                    if (!Page.IsPostBack)
                    {
                        //Profile
                        GetProfile();

                        if (Session["emp_app"] != null && !string.IsNullOrEmpty(Session["emp_app"].ToString()))
                        {
                            BindAvailableSystems(Session["emp_app"].ToString());
                        }

                        BindMainSystems();

                        if (GetLinkedApp > 0)
                        {
                            rlv_available_sys.Visible = true;
                            h5_app.Visible = true;
                            lbtn_addApp.Visible = false;
                            h4_app.Visible = false;
                            intro.Visible = true;

                        }
                        else
                        {
                            rlv_available_sys.Visible = false;
                            h5_app.Visible = false;
                            lbtn_addApp.Visible = true;
                            h4_app.Visible = true;
                            intro.Visible = false;
                        }
                        //Applications
                        if (rlv_available_sys.Visible == true)
                        {
                            Session["emp_app"] = GetLinkedApp;
                            BindAvailableSystems(Session["emp_app"].ToString());
                            if (user_flag > 0)
                            {
                                Get_UserApplicationSystems(1, 1, GetLinkedApp.ToString());
                            }
                            else
                            {
                                Get_UserApplicationSystems(user_flag, 1, GetLinkedApp.ToString());
                            }

                        }
                        //services
                        Get_MainSystems(user_flag);
                        if (GetLinkedApp > 0)
                        {
                            GetServiceInformation();
                        }
                        string[] statistics = TrackUser();
                        base.TraceActivity("Enter the portal", "https://" + Request.Url.Authority + "/AppMaster.aspx", statistics[0], statistics[1], statistics[2]);
                    }

                    TraceSystemsMode();
                }
                catch (Exception ee)
                {
                    string message = ee.Message;
                }

            }
            else
            {
                Response.Redirect("LoginPage.aspx", false);
            }
        }

My generic handler :

public void ProcessRequest(HttpContext context)
        {
            try
            {
                using(Stream photo_stream = Photo_DAL.RetrievePhoto(int.Parse(context.Session["emp_num"].ToString())))
               {
                byte[] photo_bytes = Photo_DAL.StreamToByteArray(photo_stream);
                if (photo_bytes == null)
                {
                    photo_bytes = File.ReadAllBytes(Path.Combine(context.Server.MapPath("~/images/PortalImages/"), "user.png"));
                }
                //context.Response.ContentType = "image/png";
                context.Response.BinaryWrite(photo_bytes);
                }
            }
            catch (Exception ee)
            {
            }

        }
Galvan answered 2/7, 2012 at 9:2 Comment(8)
plz tell what operation you are doing with the requestCedar
just connect to DB to bring data and insert data and get an image through generic handler ..Galvan
ok now break your code in 3 parts 1) getting data 2) inserting data and 3)image handler and run by disabling one at a time to find out which of them is taking time.Cedar
what should i do if i know that a specific part did take long time than others ? let's say the image handler ..Galvan
if u are sure it is image handler , then you should increase your execution timeout and try again, if it still dosen't work then rework on your image processing logic there is no other way out. here is a link for your help codebetter.com/petervanooijen/2006/06/15/…Cedar
I suggest that you check the windows log to see more information about the error as i think you will be able to know the reason of the iis thread termination.Bristle
Could you post the code in the handler?Ultimate
Do you know the values of INFORMIXCONTIME and INFORMIXCONRETRY environment variables on the ifx server you're connecting to?.. see:linkBelsen
K
9

This is speculation since there is a lot of referenced code that we don't get to see from that snippet posted in the question.

I am going to assume that you are not properly handling your database connections (DB_Connection_s) for a couple of reasons.

A) Fixed through reset

    I get the following errors frequently , and i had to restart the IIS or 
    republish to fix the problem temporary`

To me, this indicates that you are using all of the connections to your database up because when you restart or republish all the current connections are dropped.

B) No clear disposal

In your code, you reference DB_Connection_s, however it is not enclosed in a using block and it is not instantiated which means it is most likely a static class or method (hard to tell with no code for that reference).

Suggestion

Make sure you are always properly disposing of your database connections. They NEED to have .Dispose() called on them when finished. This is usually accomplished by taking the class that holds the context and having it implement IDisposable and then wrapping all your calls to that class with a using statement. A using statement will call the Dispose method automatically. If you prefer to not implement IDisposable you may also explicitly (not suggested) dispose of the database connection when you are through with it by calling .Dispose() directly on the connection once the query is complete.

Edit in response to newly added comments:

@just_name - From the code here in the comments, it seems to me that there could be an issue. Relying on ~DBConnection() to dispose of your connection, only calling .Close(), and not closing a stream, is what stands out to me.

i) Finalizers can take a long time

Using a finalizer to dispose of the connection can be risky because you can never be sure exactly when it is called. "The exact time when the finalizer executes during garbage collection is undefined." - MSDN Object.Finalize. This could be causing the system to wait a very long time if it has a lot of resources before any connections are disposed in turn slowing down the requests.

ii) Close is not Dispose

Although you are technically safe calling .Close() on a connection, it can cause problems in production. The reason is that the connection will close, but the event handlers will remain and sometimes if there is lazy loading involved or dynamic proxies these event handlers can hold copies of the connection.

iii) Use Dispose

a) Dispose of your connection explicitly

Always explicitly dispose of your connection, do not wait for the garbage collector to do it. The best practice way to dispose of it would be to use a using(){} block when accessing your DBConnection class. You can make a few changes to do this:

Define DBConnection to implement IDisposable so it can be used in a using block

public class DBConnection : IDisposable
{
  //other methods already in here
  public void Dispose()
  {
   //Close_Connection(); Call this if you want, but you MUST call 
   //.Dispose on your connections
   connection.Dispose();
  }
}

This will allow you to make a new DBConnection like this:

using( var DB_Connection_s = new DBConnection() )
{
 //todo: interact with database connection
}

The using block will automatically call .Dispose() when the final } is reached and dispose of the connection guaranteed. Moreover, this allows smaller transaction times to occur with the database which can increase query and request speeds if there was any queuing involved for database access.

If you do not like the using block implementation, then at the very least, change .Close() to .Dispose() everywhere that you use close and make sure that there is no possible path of execution which leads to .Dispose() not being called immediately after the database access is complete.

b) Use .Dispose() on unmanaged resources

Always use .Dispose() on unmanaged resources. There are a couple ways to do this, but the best practice way is with a using(){} block. I noticed that you could implement this in one place specifically with a stream in your code that must be handled.

This is one of the offending pieces of code:

IfxDataReader ifxDataReaders = DB_Connection.DBCmd.ExecuteReader(); 
if (ifxDataReaders.Read()) { 
 item = (int)ifxDataReaders["emp_num"]; 
} 
ifxDataReaders.Close();

I take a couple of issues with this. First, you are calling .Close() which was discussed above. Second, because this is in a try block, it is possible that ifxDataReaders can throw an exception and the program will continue to run without ever closing or disposing of the reader. This can cause many problems.

What you should do is ensure that .Dispose is always called on your unmanaged resources. You can do this with a using block (which implicitly always calls .Dispose()).

using(IfxDataReader ifxDataReaders = DB_Connection.DBCmd.ExecuteReader())
{
 if (ifxDataReaders.Read()) { 
  item = (int)ifxDataReaders["emp_num"]; 
 } 
}
Kimi answered 9/7, 2012 at 23:53 Comment(14)
DB_Connection_s it 'sn't the class used to handle the db operations although the name confuses somewhile .all the connections are closed in the finally statement or at the end of operation in my db layer .is this not enough ?!Galvan
i add the code relates to bring the user image (generic handler).Galvan
Example for how i handle the connection :Galvan
try { if (DB_Connection.conn.State == 0) { DB_Connection.conn.Open(); } DB_Connection.DBCmd = new IfxCommand(); DB_Connection.DBCmd.Connection = DB_Connection.conn; DB_Connection.DBCmd.CommandText = "-----"; DB_Connection.DBCmd.Parameters.Add("user_name", IfxType.VarChar); DB_Connection.DBCmd.Parameters["user_name"].Value = pU; DB_Connection.DBCmd.Parameters.Add("password", IfxType.VarChar); DB_Connection.DBCmd.Parameters["password"].Value = DB_Connection.My_Encryption(str);Galvan
IfxDataReader ifxDataReaders = DB_Connection.DBCmd.ExecuteReader(); if (ifxDataReaders.Read()) { item = (int)ifxDataReaders["emp_num"]; } ifxDataReaders.Close(); } catch (ApplicationException applicationException) { } DB_Connection.conn.Close(); return item;Galvan
public void Close_Connection() { if (connection.State == ConnectionState.Open) { connection.Close(); connectionstate = ConnectionState.Closed; } } /// <summary> /// Destructor /// </summary> ~DBConnection() { Close_Connection(); connection.Dispose(); }Galvan
is some thing wrong with what the code above which cause the request time out please ?Galvan
Did i need to make my DBConnection class disposable only .or should i internally in my class dispose the built in class ifxconnection also ?Galvan
one last note i use this class for a long time in many applications which used by many users more than this application and i never face this strange behavior!!Galvan
@just_name - You should be using dispose on unmanaged resources wherever they exist. As for the previous use, I am not sure why there were no issues, or perhaps they occurred rarely because of different system resources. If the issue is not the database connection, then perhaps it would be pertinent to look in a browser at how much traffic is being sent per page load. It should ideally be less than 1 MB, or 2 seconds of load time.Kimi
Could u tell me how to measure this please ?Galvan
@just_name - In firefox or google, prior to going to the page you want to measure, open firebug or the inspection console. Navigate in the console to the Net or Network tab. Then, go to the page you want to measure and look at the total traffic in the network tab.Kimi
Thanks a lot , hope this info could help me to fix this bad behavior.Galvan
Does dispose every connection sacrifice the benefit of pooling ? and is this way performance wise?Galvan
U
2

I know it do not belong to the Error Message:Request timed out but it may have a link with Error Message:Thread was being aborted.. So, as we don't have any code sample, I think it's allowed to think that it may be a Response.Redirect("aPage.aspx") issues when it's made inside of a Try-Catch block.

If it's your case, try adding a "False" to the EndResponse parameter of Response.Redirect method as shown here:

try {
    // [... SOME CODE ...]
    Response.Redirect("aPage.aspx", False)
} catch (Exception e) {
    // [... YOUR CATCH ...]
}
Unesco answered 5/7, 2012 at 20:51 Comment(0)
H
2

So I up-voted the comment from Zia suggesting you run the parts individually to isolate the timeout. Is there a chance it could be an error with the Informix connection?

Database queries have two timeouts, the connection timeout and the command timeout. Neither of these will use the executionTimeout value. I haven't tried using the Informix provider, but I have increased the timeouts on the connection object if the server is busy or the command object to wait for a long SQL query to run.

Here is a link to setting the connectionTimeout on the Informix connection object... http://publib.boulder.ibm.com/infocenter/idshelp/v115/index.jsp?topic=%2Fcom.ibm.net_cc.doc%2Fcom.ibm.swg.im.dbclient.adonet.ref.doc%2Fdoc%2FDB2ConnectionClassConnectionTimeoutProperty.htm

Hellespont answered 6/7, 2012 at 13:53 Comment(1)
i set Connection Lifetime=30; in the connection string and increase that time but in vainGalvan
I
2

The main question is, why is it taking so long? Why would some hit to a page take more than 30 seconds? Can you really go live with such a slow site ?

We have to see how to bring down the performance so that the request completes within 30 seconds.

Can you share the code? Let's see where the bottleneck is on the code.

Inexperience answered 9/7, 2012 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.