如何替换 .NET Core 2.x 中的 SqlCommand.BeginExecute

我在 .NET Framework 4.x 中使用 System.Data.SqlClient.SqlCommand.BeginExecuteReader 进行异步数据库调用,如下所示:

use! reader = Async.FromBeginEnd(CommandBehavior.SingleRow, 
         (fun (arg,callback,stateObject) -> cmd.BeginExecuteReader(callback,stateObject,arg)), cmd.EndExecuteReader)

我正在尝试将此代码迁移到 .NET Core 2.2,我发现方法“BeginExecuteReader”和“EndExecuteReader”不再可用,如此所述。.NET Core 2.2 可以使用什么来提供相同的功能?


心有法竹
浏览 176回答 1
1回答

慕少森

甚至在 .NET 4.0 中,异步执行命令的首选方法是使用ExecuteXXXAsync返回任务的方法之一。Begin/End方法用于没有 Task 的早期框架。在 F# 中,可以在异步工作流中调用ExecuteReaderAsync:let work = async {    // Open connection    use conn = new SqlConnection(connectionString)    do! conn.OpenAsync() |> Async.AwaitVoidTask    // Execute command    use cmd = new SqlCommand(queryText,conn)    use! reader = cmd.ExecuteReaderAsync() |> Async.AwaitTask    while reader.Read() do        // Consume reader        ...}work |> Async.RunSynchronouslyF# 异步工作流是在 .NET 4.0 的Task类型之前创建的,这就是为什么使用Async.AwaitTask和Async.AwaitVoidTask函数来相互采用的原因
打开App,查看更多内容
随时随地看视频慕课网APP