简体   繁体   English

C#MySQL等待上一个查询完成

[英]c# mysql wait for previous query to finish

This is part of my code in c# 这是我在C#中的代码的一部分

MySqlConnection connection = new MySqlConnection(MyConnectionString);
connection.Open();
cmd = connection.CreateCommand();
...
int xxxx;
cmd.CommandText = "UPDATE myTable SET ..... ";
xxxx = cmd.ExecuteNonQuery();
Debug.WriteLine(xxxx + " rows updated");

cmd.CommandText = "select id,... from myTable";
dr = cmd.ExecuteReader();
while (dr.Read())
...

The first query (the update) will take about 30 seconds to execute. 第一个查询(更新)将花费大约30秒的时间来执行。 What i observe, is that maybe the second query is executed before query1 having updated the table. 我观察到的是,也许第二个查询是在query1更新表之前执行的。

  • Is this what is supposed to happen according to this code? 根据代码,这应该发生什么吗?
  • Is there a way to prevent this from happening (ie complete 1st query and then execute 2nd one) 有没有一种方法可以防止这种情况发生(即完成第一个查询,然后执行第二个查询)

ExecuteNonQuery() method is synchronous and the next statement won't be executed until it is completed. ExecuteNonQuery()方法是同步的,并且下ExecuteNonQuery()语句要等到完成后才能执行。 The same applies to ExecuteReader() . 这同样适用于ExecuteReader()

Those 2 queries cannot be run in parallel in the code above (at least from one thread. If the code above is running on multiple threads, it can happen). 这两个查询不能在上面的代码中并行运行(至少从一个线程运行。如果上面的代码在多个线程上运行,则可能会发生)。

There are also corresponsing asynchronous methods ExecuteNonQueryAsync() and ExecuteReaderAsync() but they are not use in the code above. 也有相应的异步方法ExecuteNonQueryAsync()ExecuteReaderAsync()但在上面的代码中未使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM