mysql 异步 同步 不支持_MySQL C#异步方法不起作用?
我在服務器中有一個數據庫,似乎async方法不起作用.
這是我的代碼:
static async void Example()
{
string connectionString =
"Server=mydomainname.com;" +
"Port=3306;" +
"Database=scratch;" +
"Uid=Assassinbeast;" +
"Password=mypass123;" +
"AllowUserVariables= true;";
MySql.Data.MySqlClient.MySqlConnection sqConnection = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
await sqConnection.OpenAsync();
Console.Write("Opened. Now Click to close");
Console.ReadLine();
sqConnection.Close();
}
static void Main(string[] args)
{
Console.ReadLine();
Example();
Console.WriteLine("Done");
Console.ReadLine();
}
在“await”語句中,它實際上應該跳回Main()函數并寫出“Done”.但它不這樣做.它只是同步運行,就像它不是異步方法一樣,一旦功能完全完成,它將首先寫入“完成”.
那我做錯了什么?這是一個錯誤嗎?
UPDATE
好的,所以在我得到一些答案之后,我實際上仍然看不到OpenAsync()和Open()之間的任何區別.
我開始嘗試測試更多的東西,我想我可以得出結論,異步方法不起作用
這是我的新代碼:
static async Task Example()
{
string connectionString =
"Server=mydomainname.com;" +
"Port=3306;" +
"Database=scratch;" +
"Uid=Assassinbeast;" +
"Password=mypass123;" +
"AllowUserVariables= true;";
using (var sqConnection = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
{
Console.WriteLine("Opening");
await sqConnection.OpenAsync();
Console.WriteLine("Opened. Now Closing");
}
}
static async Task Example2()
{
//Lets pretend this is a database that my computer will try to connect to
Console.WriteLine("Opening");
await Task.Delay(1000); //Lets say it takes 1 second to open
Console.WriteLine("Opened. Now Closing");
}
static void Main(string[] args)
{
Console.ReadLine();
Task.Run(() => Example());
Task.Run(() => Example());
Task.Run(() => Example());
Task.Run(() => Example());
Task.Run(() => Example());
Task.Run(() => Console.WriteLine("Done"));
Console.ReadLine();
}
這里當我運行Example()5次時,它將輸出如下:
它需要3秒才會寫出“完成”.
請注意,我的計算機根本不在CPU上工作,因為它只等待并連接到數據庫,大約需要1秒才能連接到.
所以它實際上阻止了我的計算機線程并且沒有運行多線程,否則它會立即寫出“完成”.
所以如果我調用Example2()而不是Example(),那么我得到的結果就是我想要的和我期望的結果:
在這里,它是真正的異步方法,因為我可以在我的計算機上一次完成6件事,只有2個核心.
但是第一個例子,我一次只能做兩件事,因為MySQL異步方法不起作用.
我還使用sqConnection.Open()測試了它,它與sqConnection.OpenAsync()具有完全相同的結果
所以現在,我只是想弄清楚如何同時連接數據庫5次.
總結
以上是生活随笔為你收集整理的mysql 异步 同步 不支持_MySQL C#异步方法不起作用?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iis7php怎么301重定向,iis7
- 下一篇: java正则表达式匹配xml标签_用正则