mysql-net / MySqlConnector

MySQL Connector for .NET
https://mysqlconnector.net
MIT License
1.39k stars 333 forks source link

What is right way to run in mutil thread and connectpool? #741

Closed orangeagain closed 4 years ago

orangeagain commented 4 years ago

I want to use mysql in MircoSoft.orleans,orleans is large Concurrency framework.That is mean sqlrequest will send by difference thread one time. I am new here and don't know right way to use this library,do you have Sync and Async thread safe function example?

orangeagain commented 4 years ago

is this right?

`public class Program { public static async Task Main(string[] args) { var tasks = new List(); for (var i = 0; i < 1000; i++) { tasks.Add(Controllers.SleepOne()); } // these 100 queries should all complete in around // 1 second if "Max Pool Size=100" (the default) await Task.WhenAll(tasks); } }

public class Controllers
{
    public static async Task SleepOne()
    {
        using (var db = new AppDb())
        {
            await db.Connection.OpenAsync();
            using (var cmd = db.Connection.CreateCommand())
            {
                cmd.CommandText = @"SELECT SLEEP(1)";
                await cmd.ExecuteNonQueryAsync();
            }
        }
    }
}
public class AppDb : IDisposable
{
    public readonly MySqlConnection Connection;

    public AppDb()
    {
        Connection = new MySqlConnection("host=127.0.0.1;port=3306;user id=root;password=00000;database=testdb0;");
    }

    public void Dispose()
    {
        Connection.Close();
    }
}`
bgrainger commented 4 years ago

From https://mysqlconnector.net/troubleshooting/connection-reuse/

A MySqlConnection object may only be used for one operation at a time. It may not be shared across multiple threads and used simultaneously, nor reused on the same thread while there is an open MySqlDataReader.

Your example looks OK because each Task has its own MySqlConnection; they are not being shared.