You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bantflags/BantFlags/Data/MySqlConnectionPool.cs

57 lines
1.4 KiB

5 years ago
using MySql.Data.MySqlClient;
using Nito.AsyncEx;
using System;
using System.Data;
using System.Threading.Tasks;
namespace BantFlags.Data
{
public class MySqlConnectionPool : IDisposable
{
public AsyncCollection<MySqlConnection> Connections { get; }
protected string ConnectionString { get; }
protected int PoolSize { get; }
public MySqlConnectionPool(string connectionString, int poolSize)
{
PoolSize = poolSize;
ConnectionString = connectionString;
Connections = new AsyncCollection<MySqlConnection>(poolSize);
for (int i = 0; i < poolSize; i++)
{
var connection = new MySqlConnection(connectionString);
connection.Open();
Connections.Add(connection);
}
}
public async Task<PoolObject<MySqlConnection>> RentConnectionAsync()
{
return new PoolObject<MySqlConnection>(await Connections.TakeAsync(), obj =>
{
if (obj.State != ConnectionState.Open)
{
obj.Open();
}
Connections.Add(obj);
});
}
public void Dispose()
{
for (int i = 0; i < PoolSize; i++)
{
var connection = Connections.Take();
connection.Dispose();
}
}
}
}