C# Mysql Connection thread-safe

Asked

Viewed 234 times

0

I have a server that receives hundreds of asynchronous connections and I need to implement Mysql access from different threads. In fact, how I use the Async Socket Begin/End standard. Net, there is a thread pool, so it is not 1 thread for each connection and even if it was, would not create 1 Mysql connection for each threads, this would only be valid if there were at most 10 connections, being 1 Mysql connection for each connected socket.

How do I implement this? Could you suggest some study links? Do I need to use a "designe Pattern" where I have a thread-safe Mysql connection pool, where I keep x connections active and release as required? Something like:

Connection myConnection = GetSomeConnection(); // Returns a shared object
Command cmd;

lock(myConnection)
{
    cmd = myConnection.CreateCommand();
}
  • 2

    It would not be the case to implement a Singleton in the role of Broker - managing a request queue, for example? This is a commonly used model for controlling requests for unique and shared resources.

1 answer

1

It seems that a Connection pool would be a good idea. A suggestion to implement this (there must be several other answers to this problem), would be to create a class that manages the connections and this internally use a Concurrent (http://msdn.microsoft.com/pt-br/library/dd267265(v=vs.110). aspx), containing the connecting objects themselves.

The method that picks up the connections could be in a loop "while there are no connections, thread. Sleep". The time you find one, take the connection.

When finishing the thread, return the connection used for the thread. This avoids blocking between threads (no type of lock is used).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.