@@ -21,41 +21,54 @@ an open `MySqlDataReader`.
21
21
You may not execute multiple operations in parallel, for example:
22
22
23
23
``` 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;" ));
32
30
```
33
31
34
32
### Nested Access on Single Thread
35
33
36
34
You may not reuse the connection when there is an open ` MySqlDataReader: `
37
35
38
36
``` 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 ())
42
41
{
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
48
44
}
49
45
```
50
46
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
+
51
61
## How to Fix
52
62
53
63
For the multithreaded scenario, if concurrent access to the database is truly necessary,
54
64
create and open a new ` MySqlConnection ` on each thread. But in most cases, you should
55
65
just write code that sequentially ` await ` s each asychronous operation (without performing
56
66
them in parallel).
57
67
58
-
59
68
For the nested access, read all the values from the ` MySqlDataReader ` into memory, close
60
69
the 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