"await"运算符只能在异步方法中使用[MySQL连接器] [英] The 'await' operator can only be used within an async method [MySQL connector]

查看:189
本文介绍了"await"运算符只能在异步方法中使用[MySQL连接器]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与我最近的2个问题相关,这些问题最近几天已经发布在StackOverflow上.

This question is related 2 of my previous questions which have been posted on StackOverflow in last few days.

关于MySqlClient EndOfStreamException的第一个问题.

1st Question which was regarding a MySqlClient EndOfStreamException.

第一个问题

第一个问题的答案使我转向将库从MySQL ADO.NET切换到MySQL连接器.

The answer for the 1st question leads me to Switch libraries from MySQL ADO.NET to MySQL connector.

自从MySQL ADO.NET迁移到MySQL连接器以来,一些MySQL关键字出现了一些问题.我也得到了这个问题的答案.

I had some issues with some MySQL keywords since moving from MySQL ADO.NET to MySQL connector. I got the answer to that question as well.

第二个问题

现在程序正在运行,没有任何错误.但是不幸的是,由于没有将数据写入数据库,因此存在问题.

Now the program is running without any errors. But unfortunately, there is a catch since the data is not written to the database whatsoever.

为了找到解决此问题的方法,我尝试从以下代码开始向ExecuteNonQueryAsync()添加"await" 关键字.

With the intent of finding a solution to this issue I tried to add "await" keyword to ExecuteNonQueryAsync() as of the below code.

 private bool OpenConnection()
        {
            try
            {
                //connection.Open(); //line commented
                 **await connection.OpenAsync();**
                Console.WriteLine("MySQL connected.");
                return true;
            }
            catch (MySqlException ex)
            {

             }   





public void Insert()
            {
                    if (this.OpenConnection() == true)
                    {
                          using(var reader = new StreamReader(@"C:\Users\Admin\source\Bargstedt.csv"))
                    {
                    //List<string> listA = new List<string>();


                        while (!reader.EndOfStream)

                        {
                        ***await reader.OpenAsync();***

                        var line = reader.ReadLine();
                            var values = line.Split(',');
                            string querynew = "INSERT INTO jobs"
                                      + "(nJobNumber,strClientReference,datPromisedDelivery)" 
                                      + "VALUES (@jobNo, @strClientName, @strClientReference)";


                        var cmd = new MySqlCommand();

                        cmd.CommandText= querynew;




                        cmd.Parameters.AddWithValue("strClientName", "MySqlDbType.VarChar").Value =(values[1]);
                                cmd.Parameters.AddWithValue("strClientReference", "MySqlDbType.VarChar").Value = values[2];



                    ***await cmd.ExecuteNonQueryAsync();***
                        // cmd.ExecuteNonQueryAsync(); //Line commented

                    }
                    }
                    this.CloseConnection();
                }



        }

在执行此操作之前,我认为问题出在执行行上,因为任何数据都不会写回到数据库中.

Before implemented this, I reckoned the issue was with the execution line since any of the data isn't written back to the database.

这就是说服我包括 await 打开并执行源代码行的原因,此

That is the reason it persuades me to include await open and execute lines to the source code likewise given in this example.

不幸的是,在我使用过 await 关键字的所有地方(在上面的代码中突出显示)都触发了错误:

Unfortunately, in all the places I have used await keyword (Highlighted in the above code) is triggering an error:

错误CS4032'await'运算符只能在异步中使用 方法.考虑使用'async'修饰符标记此方法,然后 将其返回类型更改为任务".

Error CS4032 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

如何解决此问题,您认为数据库未更新的原因是什么?

How to fix this issue and what do you think the reason which the database is not updating?

是否可以正确实施此'await'方法?

would it be fixed if this 'await' method implemented correctly?

推荐答案

异步代码更加复杂.我建议您坚持使用(完全支持的)同步方法,直到您的数据库代码正常工作为止.因此,将await connection.OpenAsync();更改为connection.Open();,将await cmd.ExecuteNonQueryAsync();更改为cmd.ExecuteNonQuery(),等等.

Asynchronous code is more complicated. I would recommend that you stick with the (fully supported) synchronous methods until you get your database code working. So change await connection.OpenAsync(); back to connection.Open();, await cmd.ExecuteNonQueryAsync(); to cmd.ExecuteNonQuery(), etc.

(不要在不使用await语句的情况下调用Async方法,因为它会在您的主要方法保持运行的同时继续在后台执行,这可能会导致在两个单独的线程上同时使用同一连接,导致错误.)

(Don't call an Async method without using an await statement, because it will keep executing in the background while your primary method keeps running, which may cause the same connection to be used simultaneously on two separate threads, causing an error.)

您提供的示例代码未为@jobNo添加参数值.这将导致异常,因为未定义参数.

The example code you gave doesn't add a parameter value for @jobNo. That will cause an exception because the parameter isn't defined.

代码cmd.Parameters.AddWithValue("strClientName", "MySqlDbType.VarChar").Value =(values[1])错误地添加了带有文字字符串值"MySqlDbType.VarChar"的参数,然后将其覆盖.编写cmd.Parameters.AddWithValue("strClientName", values[1]);会更直接.

The code cmd.Parameters.AddWithValue("strClientName", "MySqlDbType.VarChar").Value =(values[1]) is incorrectly adding a parameter with the literal string value "MySqlDbType.VarChar", then overwriting it. It would be more straightforward to write cmd.Parameters.AddWithValue("strClientName", values[1]);.

一旦您的数据库代码正常工作,并且想要切换到异步,则可以在方法主体内使用await,然后使用async关键字(例如,private async Task<bool> OpenConnection())重新声明方法签名.

Once you get your database code working, and want to switch to async, you can use await within the method body, then redeclare the method signature with the async keyword, e.g., private async Task<bool> OpenConnection().

这篇关于"await"运算符只能在异步方法中使用[MySQL连接器]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆