C#SQL连接OpenAsync不是异步的 [英] C# SQL connection OpenAsync is not asynchronous
问题描述
我正在尝试异步打开与SQL Server的连接,以免占用UI线程.但是我发现对 connection.OpenAsync()
的调用在打开连接之前不会返回,与 connection.Open()
完全一样.
I'm trying to open a connection to an SQL server asynchronously, so as not to tie up the UI thread. But I've found that the call to connection.OpenAsync()
does not return until the connection has been opened, exactly as with connection.Open()
.
此代码重现了该问题:
public static void Main(string[] args)
{
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.UserID = "sa";
builder.Password = "1234";
builder.DataSource = "192.168.1.254\\SQLEXPRESS";
builder.InitialCatalog = "MyDatabase";
builder.PersistSecurityInfo = true;
DbConnection connection = new System.Data.SqlClient.SqlConnection(builder.ConnectionString);
Console.WriteLine("about to connect");
Task connection_task = connection.OpenAsync();
Console.WriteLine("started");
while (!connection_task.IsCompleted && !connection_task.IsFaulted && !connection_task.IsCanceled)
{
Console.WriteLine("busy");
}
Console.WriteLine("done");
}
在这种情况下, 192.168.1.254
不存在.消息关于连接
会立即出现,但是在等待连接超时时什么也没有发生,然后在连接超时后,消息 started
和 done
同时出现.我希望消息 started
会在消息关于要连接的
之后立即出现,然后消息 done
将在连接超时后稍后出现.
In this case, 192.168.1.254
is non-existent. The message about to connect
appears immediately, but then while waiting for the connection to time out nothing happens, then after the connection times out the messages started
and done
appear at the same time. I would expect that the message started
would appear immediately after the message about to connect
, then the message done
would appear later once the connection has timed out.
I'm guessing that I'm doing something wrong with the returned Task
, but the Microsoft page on Task-based Asynchronous Pattern certainly implies that I should simply be able to call the OpenAsync()
method and the returned Task
will be running asynchronously, instead of the operation taking place synchronously and tying up the calling thread until the Task
completes.
推荐答案
事实证明,这是Mono运行时中的错误,并且代码在Microsoft .NET上运行良好.MySQL .NET库( MySql.Data
)似乎也存在类似的错误,无论使用Mono还是Microsoft .NET运行时,该库都能同步运行任务.
It turns out that this is a bug in the Mono runtime and that the code works fine on Microsoft .NET. A similar bug also seems to be present with the MySQL .NET library (MySql.Data
), which runs the task synchronously regardless of whether the Mono or the Microsoft .NET runtime is used.
我已经找到有关该问题的错误报告MySQL.
I've found a bug report for the issue with MySQL.
这篇关于C#SQL连接OpenAsync不是异步的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!