Question

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():
Was it helpful?

Solution

Try to use:

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

OTHER TIPS

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)

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top