【发布时间】:2013-09-13 19:55:05
【问题描述】:
我在 dapper 中尝试了异步支持,在运行一个简单的用例时遇到了以下问题。我有一个 ApiController ,它使用 dapper 触发日志条目以在数据库中创建它。我的数据库连接很好。当我使用 dapper 的 Query 扩展方法运行同步版本时,一切正常。当我将 QueryAsync 与 async/await 结构一起使用时,我得到一个 InvalidOperationException。这是代码的样子
public class BackgroundController : ApiController
{
[HttpGet]
public async Task<HttpResponseMessage> Run(string op)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Backgrounder"].ConnectionString))
{
const string sql =
"Insert Into SimpleLog (message, threadid, created) Values(@message, @threadid, @created); " +
"SELECT CAST(SCOPE_IDENTITY() as int)";
var results = await (connection.QueryAsync<int>(sql, new { message = "new log record", threadid = "1", created = DateTime.Now }));
var id = results.SingleOrDefault();
Debug.WriteLine("inserted log record id: " + id);
}
return this.Request.CreateResponse(HttpStatusCode.OK);
}
}
此外,堆栈跟踪如下所示:
在 System.Data.SqlClient.SqlCommand.b_24(Task1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
在 System.Threading.Tasks.Task.Execute()
--- 从先前抛出异常的位置结束堆栈跟踪 ---
在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Dapper.SqlMapper.<QueryAsync>d__691.MoveNext() 在 c:\Dev\Dapper\Dapper NET45\SqlMapperAsync.cs:line 21
--- 从先前抛出异常的位置结束堆栈跟踪 ---
在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
在 WebApiBackgrounder.Controllers.BackgroundController.d_0.MoveNext()
当 dapper 调用 ExecuteReaderAsync 时,它似乎失败了。有谁可以解决这个问题?
编辑
这是连接字符串
<add name="Backgrounder" providerName="System.Data.SqlClient" connectionString="Data Source=LPW7X6530;Initial Catalog=Sandbox;Integrated Security=SSPI;" />
【问题讨论】:
-
异常的信息是什么?
-
你的连接字符串是否包含
Asynchronous Processing=True? -
@MarcGravell 我以前没有,但添加它也不能防止异常
-
@svick 消息是“无效操作。连接已关闭。”
-
@cecilphillip 如果您先打开连接,它可以工作吗?
标签: asp.net-web-api async-await dapper