Thanos Darkadakis
Thanos Darkadakis

Reputation: 1729

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.

Upvotes: 1

Views: 3120

Answers (1)

Szymon
Szymon

Reputation: 43023

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.

Upvotes: 1

Related Questions