locked
Debug Program RRS feed

  • Question

  • Hi Experts

                                I wrote a program which is very simple. It run well and provide perfect output. But after sometime like 1 hour or 2 or 3 hours and some time after 5 hours program hangs. It went into nor responding mode. I did everything but could not found the error. Can anyone help me please

    try  
                {
    
                   msg1 = "\n Starting Process: \n";
    
                while (true)
                {
    
                    iGrafikUzunlugu = getGraphLengthM1();
                    iGrafikUzunlugu2 = getGraphLengthM2();
                    try
                    {
                        if (m_Server == null)
                        {
                            OnConnect("opcda://localhost/OPC.SimaticNet");
                        }
                        if (m_Server.IsConnected)
                        {
                            msg2 = "\n 1. Connection completed! ";
    
                            StringCollection sc = new StringCollection();
    
                            sc.Add("S7:[S71200_Conn]DB2,X0.0");
                            SendParam(sc, "READ", -1);
                            bool refresh = Convert.ToBoolean(values[0].ToString());
    
                            msg3 = "\n 2. Reading Data From OPC completed! ";
    
                            if (refresh)
                            {
                                sc.Clear();
    
                                fM1Pozisyon = new float[iGrafikUzunlugu];
                                fM1Tork = new float[iGrafikUzunlugu];
                                OlcumZamani = new float[iGrafikUzunlugu];
                                int size = iGrafikUzunlugu * 4;
    
    
                                for (int i = 0; i < size; i += 4)
                                    sc.Add("S7:[S71200_Conn]DB2,REAL" + (i + 4));
                                SendParam(sc, "READ", -1);
                                for (int i = 0; i < iGrafikUzunlugu; i++)
                                {
                                    fM1Tork[i] = (float)Convert.ToDouble(values[i].ToString());
    
                                    if (fM1Tork[i] < 50) //Changed it from 200 just a test case 
                                        //Console.WriteLine(i+") *********************************Small value appeared: "+fM1Tork[i]);
                                        MessageBox.Show(i + ") Tork Error Small value appeared... " + fM1Tork[i]);
    
                                }
                                sc.Clear();
    
                                for (int i = 0; i < size; i += 4)
                                    sc.Add("S7:[S71200_Conn]DB2,REAL" + (i + 4004));
                                SendParam(sc, "READ", -1);
                                for (int i = 0; i < iGrafikUzunlugu; i++)
                                    fM1Pozisyon[i] = (float)Convert.ToDouble(values[i].ToString());
    
                                sc.Clear();
    
                                for (int i = 0; i < size / 2; i += 2)
                                    sc.Add("S7:[S71200_Conn]DB2,WORD" + (i + 8004));
                                SendParam(sc, "READ", -1);
                                for (int i = 0; i < iGrafikUzunlugu; i++)
                                    OlcumZamani[i] = Convert.ToInt32(values[i].ToString());
    
    
                                msg4 = "\n 3. Graph completed! ";
    
                                displayGraph();
                                displayRefresh();
                                M1RefreshTime = DateTime.Now.ToString();
                                makeRefreshFlagFalse();
    
                                msg5 = "\n 4. Display Graph and Refresh completed! ";
    
                                //Lets Save data in Database automatically
    
                                try
                                {
                                    string prodName = DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToLongTimeString();
                                    Int32 newProdID = 0;
    
                                    using (SqlConnection conn = new SqlConnection(connectionString))
                                    {
                                        conn.Open();
    
                                        string sql = "INSERT INTO [dbo].[Product] VALUES ('" + prodName + "', 1, convert(date, GETDATE()), convert(time, GETDATE())); SELECT CAST(scope_identity() AS int)";
    
                                        using (SqlCommand command = new SqlCommand(sql, conn))
                                        {
                                            newProdID = (Int32)command.ExecuteScalar();
                                        }
                                        //}
    
                                        sql = "";
                                        for (int i = 0; i < iGrafikUzunlugu; i++)
                                        {
                                            sql += "INSERT INTO [dbo].[Tork_PositionValues] VALUES (" + (int)newProdID + ", " + fM1Tork[i] + " , " + fM1Pozisyon[i] + "," + OlcumZamani[i] + ");";
                                        }
    
                                        using (SqlCommand command = new SqlCommand(sql, conn))
                                        {
                                            command.ExecuteNonQuery();
                                        }
    
                                        conn.Close();
    
                                    }
    
                                    msg6 = "\n 5. Database Insertion completed! \n\n Job No."+ (count+1) + " Completed!";
                                    count++;
                                    S1Message = "İşlem Başarılı! " + count;
    
                                    
    
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Error: " + ex.Message);
                                }
    
                            }
                            
                        }
                        else
                            MessageBox.Show("Not Connected!");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    } 
    
               
                    //Thread.Sleep(1000); Test Commenting by Aziz on December 03, 2014
                    
                }
    
                } //Aziz Try End Test case December 03 2014
                catch (Exception ex)
                {
                    MessageBox.Show("Bull Error: TAKE PICTURE! if you got this error... " + ex.Message);
                }



    • Edited by Azizsagi Tuesday, December 9, 2014 7:48 AM Complete Source Code
    Monday, December 8, 2014 2:36 PM

Answers

  • Changing the loop logic isn't going to solve any hanging issues.  Hanging means you are stuck on a blocked call.  Looking at your code the SendParams() and DB calls are the only ones that would hang for any length of time. I recommend that you run your app in the debugger and when it hangs break into the app to see where it is at.

    Alternatively if you cannot use the debugger and see the hang then run the app normally but when it hangs then use Task Manager to debug the process. At any rate you'll be able to see what your code is doing and see where the hang is. 

     
    • Marked as answer by Kristin Xie Tuesday, December 16, 2014 9:01 AM
    Wednesday, December 10, 2014 4:42 PM

All replies

  • "I wrote a program which is very simple. "

    Then, please provide the entire source code file so readers here can put your program in Visual Studio to analyze it.

    You can upload the source code file to a public site, like OneDrive, then post the link here.

    Monday, December 8, 2014 3:49 PM
  • Based upon your code you are potentially going to wear out the CPU because your loop runs continually.  Is that the problem you're seeing? Additionally if you lose a connection to the server then IsConnected is false so you'll go into a tight loop because you never recover from the disconnected state (which could happen after the app runs for a while or the remote end restarts). Your logic to connect to the server would only run the first time because it checks for null. I'd wager that you need to add more logic to the "disconnected" state to clean up the connection (closing it and resetting your field to null) so that the next time through the loop you'll attempt to reconnect.

    Michael Taylor
    http://blogs.msmvps.com/p3net

    Monday, December 8, 2014 4:43 PM
  • Thanks Michael

                                I have put the connection in if and else like

    if (m_Server.IsConnected)
                        {
                              // statements;
                        }
    else
                       {
                         messageBox.Show("Not Connected...");
                       }
    will this not work when connection disconnect?

    Tuesday, December 9, 2014 6:20 AM
  • Sure... 
    Tuesday, December 9, 2014 6:20 AM
  • Hi Michael

                        I have checked the loops. It run only when the thread refresh. The code I showed up is running inside a thread.

    Tuesday, December 9, 2014 11:30 AM
  • Based upon your updated code you would get a MB if the server wasn't connected anymore. But you mentioned you have this running on a separate thread. If you have this code in a separate thread then, depending upon what thread that is, you might or might not see the MB.  MB is not the correct way to debug code. In fact it is one of the worst ways to do so as it doesn't convey any useful information, modifies the program under test and doesn't work in all cases.

    Use the Debug class to log messages to the debug window to help track state while developing and/or Trace for production tracing. Additionally step through your code using the debugger to help understand how your code is working and where things go wrong.

    Since you have to run your app for a while before it fails you can either run the app in the debugger and wait for the server to disconnect before breaking into the code or run your app and then disconnect the network to cause a simulated failure. At that point you can step through your code and see how it behaves.

    Tuesday, December 9, 2014 2:40 PM
  • Thanks for your comments. You are right I have used MB for debugging which is not the good way to do. If you see I have used While(true) statement in the start. And I didn't use any break statement. Can this cause the hanging of my application? Maybe loop turns to be infinite some time.

    1. I have disconnected from server and got error program didn't hang

    It means that disconnected from server is not causing the hanging. Most probably it is the loop. I am testing it right now. If you can give me your thoughts I will be very grateful to you.

    Thanks

    Tuesday, December 9, 2014 3:06 PM
  • break statements are used to execute a loop.  What causes your code to run forever is the while(true) which is an infinite loop.  That logic is fine if you want it to run forever. 

    It isn't clear what the context is for this code. I'm assuming that this code is part of a method that you want to run forever in a secondary thread. If so then it is fine.  Each time through the loop you'll check to see if the server is connected and do some work if it is.  The part you're missing is what happens if it isn't. In that case I think you should try to reconnect but perhaps you want the thread to terminate instead. In that case a break statement will get you out. But then your thread terminates (based upon my assumption above) and you'd need to create a new thread if you wanted to reconnect again.

    What is the desired behavior when the server connection fails?  Do you want to terminate your thread? If so then use a break statement if the connected check fails. If you want to try to connect again then add the reconnect logic in lieu of the break statement.

    If you eventually want to get out of the loop (maybe because your app wants to terminate) then you'll need to add logic for that. A simple approach is to add a ManualResetEvent that you check inside of while(true). This is also a convenient place to put a delay between each iteration of the loop. As an example.

    //Defined in some accessible location like the class that manages the loop
    ManualResetEvent m_evtTerminate = new ManualResetEvent(false);
    
    //Inside your thread code that should loop until you terminate your app - wait 1 second and then run the loop again
    while (!m_evtTerminate.WaitOne(1000))
    {
       try
       {
          //Try to connect if not connected yet
          if (!m_server.IsConnected)
          { 
            //Do your connect work here
          };
          
          //If connected do real work
          if (m_server.IsConnected)
          {
             //Do real work
          };
        } catch 
        {
           //Do error handling here but don't cause the 
           //loop to terminate
        };
    }
    
    //Elsewhere in your app when you want to terminate the thread gracefully - maybe in your app close handler
    m_evtTerminate.Set();
    Tuesday, December 9, 2014 4:31 PM
  • Hi

            Thanks for your help. I have applied checks on server connection. And There is a While(true) infinite loop that is needed so it run always and then refresh check. Simple stuff I dont know why program hangs and there is no error.

    I got your idea and its logical to put loop on wait for 1 sec. I am going to try it and lets see what will happen

    Thanks a lot again.

    Tuesday, December 9, 2014 6:17 PM
  • Ensure that your try-catch is inside the loop and that you're logging to Debug or something when an exception occurs. That way if something errors out you'll see it but still try to continue.
    Tuesday, December 9, 2014 6:48 PM
  • I see... Okay I will put try catch inside the loop. This is the main problem that I can't see any error. I have put every section of code inside the try catch. How can I debug it?
    Tuesday, December 9, 2014 6:59 PM
  • The proper approach to debugging is running it in the debugger and let the debugger catch the exception. It'll then alert you. But for that to work you wouldn't be using a try-catch. To break into the debugger when an exception occurs and the catch block is called then put a breakpoint in your catch block. As soon as the exception occurs it'll hit the breakpoint and the debugger will pause.
    Tuesday, December 9, 2014 8:23 PM
  • Okay I am adding loop to wait for 1 sec. I have added it like this

    while(true) ---> changed it to  while (!m_evtTerminate.WaitOne(1000))

    is it a good approach?

    Wednesday, December 10, 2014 6:19 AM
  • Hi

                I put the loop to wait for 1 sec but still it hangs after 2 hours. This is really strange.

    Wednesday, December 10, 2014 1:27 PM
  • Changing the loop logic isn't going to solve any hanging issues.  Hanging means you are stuck on a blocked call.  Looking at your code the SendParams() and DB calls are the only ones that would hang for any length of time. I recommend that you run your app in the debugger and when it hangs break into the app to see where it is at.

    Alternatively if you cannot use the debugger and see the hang then run the app normally but when it hangs then use Task Manager to debug the process. At any rate you'll be able to see what your code is doing and see where the hang is. 

     
    • Marked as answer by Kristin Xie Tuesday, December 16, 2014 9:01 AM
    Wednesday, December 10, 2014 4:42 PM
  • Hi CoolDadTx

               Thanks again for your assistance. I have a question and that is,  How can I identify the process in task manager? and how can i check from task manager that where my App hangs?

    Thanks

    Wednesday, December 10, 2014 8:15 PM
  • Your app process name shows up in TM. When you right click on the process (and you have VS installed) then Debug is an option so you could immediately jump into the debugger.  Alternatively use the Create Dump option to generate a full dump file.

    If VS is installed on the same machine you can alternatively use Attach to Process to attach to the process rather than using TM.

    Wednesday, December 10, 2014 9:00 PM
  • Thank you very much. I am going to try this option.

    Thursday, December 11, 2014 6:22 AM
  • Would you mind letting us know the result of the suggestion? I temporarily mark CoolDadTxs last
    response as an answer. You can unmark it if they provide no help.



    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, December 16, 2014 9:00 AM