.NET 4.5的异步function是否也适用于MySql和其他数据库?

据我所知,.NET 4.5附带了许多function,可以使异步数据库操作更容易实现。 MSDN说如果连接字符串没有设置为异步工作,ADO.NET的异步方法都不会以异步方式工作。 因此,SqlConnectionStringBuilder附带了一个名为AsynchronousProcessing的属性。

我想知道这些异步function是否也适用于其他数据库服务器(例如mysql)? 如何使用.NET无法识别的无SQL数据库进行异步操作? (例如RavenDB)?

所有驱动程序的异步方法都在DbDataReader中定义,例如DbDataReader.ReadAsync 。 特定的驱动程序可以通过特定的实现来覆盖这些方法,以利用每个数据库的异步特性并使用例如。 自然异步操作而不是包含在线程中的同步操作。

也就是说,MySQL Connector / Net 6.8增加了对Entity Framework 6中异步操作的支持,但MySqlDataReader类不提供ReadAsync方法。 这是因为Connector使用旧架构(2.0之前版本),实现IDataReader接口,而不是从.NET 2.0中引入的通用DbDataReader类派生。

由于Panagiotis Kanavos提到DbDataReader提供了ReadAsync方法签名,但并非所有驱动程序都支持此function。 有些像MySql 6.9.5驱动程序一样同步实现它们。

要回答更一般的问题,如果(No)SQL驱动程序本身不支持*等待的Async方法,但它确实有基于“APM”IAsyncResult的方法(例如BeginRead .. EndRead …),那么你可以包装那些使用Task.Factory.FromAsync。 以下是MySql的示例: –

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

在MSDN上更详细地描述了这种模式。

我今天遇到了同样的问题,我制作了一个控制台应用程序来测试它是否正常工作。 在我看来,它不适用于我的MySQL连接器6.9.4。

 using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MySQLTest { class Program { static void Main(string[] args) { Service service = new Service(); var task1 = service.GetCountries("1"); var task2 = service.GetCountries("2"); var task3 = service.GetCountries("3"); Console.WriteLine("bö"); Console.ReadLine(); } } public class Service { public async Task> GetCountries(string param) { Console.WriteLine(String.Format("{0} started.", param)); using (worldEntities context = new worldEntities()) { Console.WriteLine(String.Format("{0} awaiting.", param)); List countries = await context.country.ToListAsync(); Console.WriteLine(String.Format("{0} done.", param)); return new List(); } } } } 

这个输出,

OUTPUT1

当我更改List countries = await context.country.ToListAsync();

等待Task.Delay(5000);

它的结果是:

OUTPUT2

5秒后。

所以我说它还没有得到支持。