views:

81

answers:

4

what is the proper way of closing a tread after running a query against a MySql database from a windows form in C#.

is a simple open close enough like this?

conn.Open();

//querycode

conn.Close():
+3  A: 

Try to use:

using(MySqlConnection conn = new MySqlConnection(connString))
{
    conn.Open();
} // conn is automatically closed and disposed at the end of the using block
Justin Niessner
A: 

Classes that use resources that you need to clean up afterwards usually implement the IDisposable interface. This means it provides a function called Dispose() that can be used to free resources.

For disposable objects, you can use the using statement:

using ( SomeDisposableClass c = new SomeDisposableClass() ) {

    // ... your code here

} // c.Dispose() automatically called here, freeing up resources

If the class is properly coded, it should free any resources -- be it a database connection, an opened file handle, etc -- in its Dispose() function.

This means that the MySQL probably disconnects from the database in Dispose(), so you probably don't need to explicitly call c.Close() -- but always check the documentation to be sure.

csl
A: 

it is okay the way you are doing it, you can also wrap connection object into using block like this:

using (var con = new MySqlConnection(/*connection string*/))
{
    con.Open();
    //do stuff
    // con.Close(); //don't need this it will be closed automatically* 
}

(*see)

TheVillageIdiot
con.Close(); is redundant here.
Joel Coehoorn
for me it dont seem redundant because my app seems ot build more and more treads as im browing the MySql db from my tool.
Darkmage
A: 

No, the code in your question is not good enough. If your query throws an exception you won't Close() it in a timely manner and it will be left hanging until the garbage collector notices it.

You need to enclose the object in a using block as shown by others or at a bare minimum encase it in a try/finally structure.

Joel Coehoorn