問題描述
我正在嘗試使用 async/await 將一些記錄插入到數據庫中.如果我不手動打開連接,我會收到 Exception
.如果我添加一些代碼來打開連接,那么一切正常.
這是當前代碼(拋出異常):
using (var connection = new SqlConnection(ConnectionString)){var tasks = new List();sellUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url)));rentUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url)));等待 Task.WhenAll(tasks);}...私有異步任務 InsertUrlAsync(IDbConnection 連接,字符串 url){const string query = "INSERT INTO ..";return await connection.ExecuteAsync(query, new { .. });}
異常:
<塊引用>消息:System.InvalidOperationException:操作無效.連接已關閉.
但是當我將代碼更改為以下內容時,它起作用了:
var tasks = new List();等待 connection.OpenAsync();sellUrls.ForEach(....) .. 等等...
類似的問題:
- Task.WhenAll,連接正在關閉
- SqlConnection 在 using 語句中意外關閉
Dapper 為您打開連接;但它也會在工作完成后關閉它.
現在,您正在使用一個連接運行兩個獨立的 async
任務.
soldUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url)));rentUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url)));
兩個任務同時運行.當一項任務的工作完成時,它關閉連接.但是其他任務仍在運行,它不再有權訪問打開的連接,因此出現了您提到的異常.
如您所說,如果您自己打開連接,Dapper 不會關閉它,一切正常.
順便說一下,在并發使用連接實例時,可能會出現意想不到的問題.請參閱此問題了解更多詳情.
I'm trying to use async/await to insert a number of records into a database. If I don't manually open the connection, I get an Exception
. If I add some code to open the connection, then everything works ok.
Here's the current code (which throws an Exception):
using (var connection = new SqlConnection(ConnectionString))
{
var tasks = new List<Task>();
soldUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url)));
rentUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url)));
await Task.WhenAll(tasks);
}
...
private async Task InsertUrlAsync(IDbConnection connection, string url)
{
const string query = "INSERT INTO ..";
return await connection.ExecuteAsync(query, new { .. });
}
the exception:
Message: System.InvalidOperationException : Invalid operation. The connection is closed.
but when I change the code to the following, it works:
var tasks = new List<Task>();
await connection.OpenAsync();
soldUrls.ForEach(....) .. etc ...
Similar SO questions:
- Task.WhenAll, connection is closing
- SqlConnection closes unexpectedly inside using statement
Dapper opens the connection for you; but it also closes it when work is done.
Now, you are running two independent async
tasks using one single connection.
soldUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url))); rentUrls.ForEach(url => tasks.Add(InsertUrlAsync(connection, url)));
Both the tasks are running simultaneously. When work of one task finish, it closes the connection. But other task is still running which does not have access to open connection anymore and hence the exception you mentioned in question.
As you said, if you open the connection yourself, Dapper does not close it and everything just works fine.
By the way, while using connection instance concurrently, there may be unexpected issues. Please refer to this question for more details.
這篇關于為什么我需要手動打開這個 .NET Core 數據庫連接,而通常 Dapper 會自動打開它?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!