@@ -21,41 +21,54 @@ an open `MySqlDataReader`.
2121You may not execute multiple operations in parallel, for example:
2222
2323``` csharp
24- using (var connection = new MySqlConnection (" ..." ))
25- {
26- await connection .OpenAsync ();
27- await Task .WhenAll ( // don't do this
28- connection .ExecuteAsync (" SELECT 1;" ),
29- connection .ExecuteAsync (" SELECT 2;" ),
30- connection .ExecuteAsync (" SELECT 3;" ));
31- }
24+ using var connection = new MySqlConnection (" ..." );
25+ await connection .OpenAsync ();
26+ await Task .WhenAll ( // don't do this
27+ connection .ExecuteAsync (" SELECT 1;" ),
28+ connection .ExecuteAsync (" SELECT 2;" ),
29+ connection .ExecuteAsync (" SELECT 3;" ));
3230```
3331
3432### Nested Access on Single Thread
3533
3634You may not reuse the connection when there is an open ` MySqlDataReader: `
3735
3836``` csharp
39- using (var connection = CreateOpenConnection ())
40- using (var command = new MySqlCommand (" SELECT id FROM ..." , connection ))
41- using (var reader = command .ExecuteReader ())
37+ using var connection = CreateOpenConnection ();
38+ using var command = new MySqlCommand (" SELECT id FROM ..." , connection );
39+ using var reader = command .ExecuteReader ();
40+ while (reader .Read ())
4241{
43- while (reader .Read ())
44- {
45- var idToUpdate = reader .GetValue (0 );
46- connection .Execute (" UPDATE ... SET ..." ); // don't do this
47- }
42+ var idToUpdate = reader .GetValue (0 );
43+ connection .Execute (" UPDATE ... SET ..." ); // don't do this
4844 }
4945```
5046
47+ ### Dispose While in Use
48+
49+ You may not ` Dispose ` any MySqlConnector objects while they are in use:
50+
51+ ``` csharp
52+ var connection = new MySqlConnection (" ..." );
53+ await connection .OpenAsync ();
54+ var command = new MySqlCommand (" SELECT SLEEP(1)" , connection );
55+ var task = command .ExecuteScalarAsync ();
56+ connection .Dispose (); // don't do this
57+ command .Dispose ();
58+ await task ;
59+ ```
60+
5161## How to Fix
5262
5363For the multithreaded scenario, if concurrent access to the database is truly necessary,
5464create and open a new ` MySqlConnection ` on each thread. But in most cases, you should
5565just write code that sequentially ` await ` s each asychronous operation (without performing
5666them in parallel).
5767
58-
5968For the nested access, read all the values from the ` MySqlDataReader ` into memory, close
6069the reader, then process the values. (If the data set is large, you may need to use a batching
61- approach where you read a limited number of rows in each batch.)
70+ approach where you read a limited number of rows in each batch.)
71+
72+ For lifetime management, prefer to use ` using ` (or ` await using ` ) instead of explicitly
73+ calling ` Dispose ` (or ` DisposeAsync ` ). Ensure that all outstanding operations have
74+ completed before disposing objects that are in use.
0 commit comments