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次.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值