简体   繁体   中英

c# mysql wait for previous query to finish

This is part of my code in 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. What i observe, is that maybe the second query is executed before query1 having updated the table.

  • 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. The same applies to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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