C# Mysql and multiple threads?

后端 未结 1 1151
一生所求
一生所求 2021-01-06 05:01

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 s

相关标签:
1条回答
  • 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.

    0 讨论(0)
提交回复
热议问题