CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Oct 2008
    Posts
    45

    closing code bizzare behaviour

    Hi guys I'm new to C#.net so please keep that in mind.
    first I'm using VS2005 i'm also using c# for developing some data base driven windows application, Im also using MySQL as my data base,

    I used the DataGridView class (naturally) to display some data, but in order to add some other functionalities I encapsulated the DataGridVeiw calss with my own custom made class that saves the updates the user makes as sql queries (took care of sql injection) now what I needed is when the user closes the window (form) the queries saved are sent to MySQL so intuitively I did that in the class destructor:
    Code:
    ~myTable()
    {
           if(notSynchronisedQueries.Count>0) executeNonQueries(notSynchronisedQueries);
    }
    protected void executeNonQueries(List<string> Queries)
    {
           MySqlConnection connection = new MySqlConnection(connectionString);
           MySqlCommand command = new MySqlCommand();
           connection.Open();     // code stops here
           command.Connection = connection;
           comand.Type = CommandType.Text;
           for(int i=0;i<Queries.Count;i++)
           {
                   command.CommandText += Queries[i] + "\n";
           }
           command.ExecuteNonQuery();
           connection.Close();
    }
    ok string connectionString is a part of my class and List<string> notSynchronisedQueries is also a part of my class myTable.

    now the problem is when the user closes the queries doesn't seem to reach the database. I tracked the code moving one statement at a time and through the use of breakpoints and noticed that the code stopped at the place indicated above it just reaches there and returns thus closing the window without updating the data base, WHY? and HOW can I solve this issue.

    I also tried putting a MessageBox in the destructor it also appears but as soon as it apears it goes away and the application continues and closses the window without me even touching the message box!!!

    my only guess is that the application is closing then the garbage collector is deleting the components but is stopped or just deletes before the destructor finishes but thats just my guess

    please help
    thanks

  2. #2
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: closing code bizzare behaviour

    I assume you are coming from a C++ background.

    In .NET destructors work in a different way. .NET framework comes with Garbage Collector (GC), which has the responsibility of freeing up resources when they go out of scope or are not in use anymore. GC basically runs a separate low priority thread and is invoked by the framework from time to time depending on how much memory has been utilized and how much is available. In practice, when a destructor is implemented in a class and there is some code written in the dtor, .NET framework does not guarantee that the code would be executed immediately when the object goes out of scope. When GC is invoked by the framework, the dtors will get executed that time.

    In C# or .NET, the dtors should be avoided and a better way of doing some action when an object is no longer used is to have a Dispose method. The Dispose method is part of IDisposable interface and the code should be written in the Dispose method and not in the dtor. It would be nice to read about how GC works, take a look at garbage Collection.

    Also as an example here is sample console application that shows how to implement Dispose method.
    Code:
    using System;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                //create a new object
                Maths myMath = new Maths();
                Console.WriteLine("Addition of 2 + 2 = {0}", myMath.Add(2, 2));
                Console.ReadLine();
                //dispose the object
                myMath.Dispose();
                Console.ReadLine();
            }
        }
    
        class Maths : IDisposable 
        {
            public Maths()
            {
                Console.WriteLine("Constructor has been called");
            }
            
        
            public int Add(int number1, int number2)
            {
                return number1 + number2;
            }
    
            public void Dispose()
            {
                Console.WriteLine("Dispose method has been called, please free up the resources here");
            }
    
            ~Maths()
            {
                Console.WriteLine("I don't know when this will be called, so don't put any clean-up code here");
            }
    
        }
    }

  3. #3
    Join Date
    Oct 2008
    Posts
    45

    Re: closing code bizzare behaviour

    well I tried it its even worse the code will not even enter the Dispose function when I close the window

    an additional note when I traced the code (using the destructor) the Form's protected override void Dispose(bool disposing) is called and when its done the code returns to the Main at the code line indicated by a HERE comment:
    Code:
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());     // HERE
            }
    then it moves out of the main and then it goes to the destructor!!! isn't that strange? then as mentioned previously does some code and then decides that it had enough and stops in the mid of the executeNonQueries(List<string> Queries) function !?!?!

    help please and thank you

  4. #4
    Join Date
    Jun 2008
    Posts
    2,477

    Re: closing code bizzare behaviour

    Why don't you simply use the FormClosing event for this?

  5. #5
    Join Date
    Oct 2008
    Posts
    45

    Re: closing code bizzare behaviour

    BigEd nailed it cool man it worked thanks

    but isn't it strange how some code still ran after main exited, strange....

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured