Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Mysql and multiple threads?

Tags:

c#

I am hosting a WCF service which uses the mysql connector. For some reason once every 5-10 minutes I get an error that mysql is already in use. What should I do? Set it up so that it blocks, have it create a new connection per thread or setup a manager which creates a set number of connections and will block until a connection becomes available. Actually do the asynchronous calls already do that last part? Lastly whats the best way to block until another thread completes and get information from that thread?

public static int Query(this IDbConnection olddb, string query, params object[] args)
{
    using (var db = olddb.CloneEx())
    {
        db.Open();
        using (var com = db.CreateCommand())
        {
            com.CommandText = query;
            for (int i = 0; i < args.Length; i++)
                com.AddParameter("@" + i, args[i]);

            return com.ExecuteNonQuery();
        }
    }
}
Unhandled Exception: System.NotImplementedException: The requested feature is not implemented.
  at MySql.Data.MySqlClient.MySqlConnection.EnlistTransaction (System.Transactions.Transaction transaction) [0x00000] in :0
  at MySql.Data.MySqlClient.MySqlConnection.Open () [0x00000] in :0
like image 609
Will Avatar asked Dec 13 '22 10:12

Will


1 Answers

Everytime you need to query your SQL server simply:

using (var conn = new MySqlConnection("Some connection string"))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT foo FROM bar";
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            // process the results
        } 
    }
}

This ensures that connections are returned into the connection pool that ADO.NET manages for you and so that you don't get any risks of creating multiple connections that could slow things up. Also this code is perfectly reentrant and thus by definition thread safe => it could be executed concurrently from as many threads as you wish.

like image 134
Darin Dimitrov Avatar answered Dec 31 '22 03:12

Darin Dimitrov