Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does .NET 4.5's async feature work with MySql and other databases too?

I understand that .NET 4.5 comes with a bunch of features to make asynchronous database operations easier to implement. MSDN says that if the connection string is not set to work asynchronously none of the async methods of ADO.NET will work in an asynchronous way. Therefore SqlConnectionStringBuilder comes with a property called AsynchronousProcessing.

I am wondering if these async features will work with other database servers (e.g. mysql) as well? What should I do to make aync work with a no-SQL database that is not recognized by .NET? (e.g. RavenDB)?

like image 790
Aref Avatar asked Feb 24 '14 03:02

Aref


2 Answers

The asynchronous methods for all drivers are defined in DbDataReader, eg DbDataReader.ReadAsync. It is up to the specific drivers to override these methods with specific implementations to take advantage of the asynchronous characteristics of each database and use eg. a naturally asynchronous operation instead of a synchronous operation wrapped in a thread.

That said, MySQL Connector/Net 6.8 adds support for asynchronous operations in Entity Framework 6 but the MySqlDataReader class does NOT provide a ReadAsync method. This is because Connector uses an old architecture (pre-2.0), implementing the IDataReader interface instead of deriving from the generic DbDataReader class introduced in .NET 2.0.

like image 159
Panagiotis Kanavos Avatar answered Sep 19 '22 12:09

Panagiotis Kanavos


As Panagiotis Kanavos mentioned DbDataReader provides ReadAsync method signatures, however not all drivers support this. Some, like the MySql 6.9.5 driver, implement them synchronously.

To answer your more general question, if a (No)SQL driver does NOT inherently support *Async methods that are awaitable, but it does have "APM" IAsyncResult based methods (e.g. BeginRead.. EndRead...), then you can wrap those up using Task.Factory.FromAsync. Here is an example for MySql:-

public static class MySqlCommandExtension
{
    public static Task<MySqlDataReader> MyExecuteReaderAsync(this MySqlCommand source, CommandBehavior behavior = CommandBehavior.Default)
    {
        return Task<MySqlDataReader>.Factory.FromAsync(source.BeginExecuteReader(behavior), source.EndExecuteReader);
    }
}

This pattern is descibed in more detail on MSDN.

like image 35
Ricardo Campos Avatar answered Sep 20 '22 12:09

Ricardo Campos