Created
October 2, 2019 19:17
-
-
Save mhagrelius/f0a7544368da76e06082059cf9300536 to your computer and use it in GitHub Desktop.
IAsyncEnumerable ADO.NET Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static async IAsyncEnumerable<IEnumerable<object?>> GetResults(this SqlConnection connection, string query, [EnumeratorCancellation] CancellationToken token) | |
{ | |
if (string.IsNullOrWhiteSpace(query)) | |
{ | |
throw new ArgumentException(nameof(query)); | |
} | |
var wasClosed = connection.State != ConnectionState.Open; | |
try | |
{ | |
if (wasClosed) | |
{ | |
await connection.OpenAsync(token); | |
} | |
using var command = new SqlCommand(query, connection); | |
using var reader = await command.ExecuteReaderAsync(token); | |
if (reader.HasRows) | |
{ | |
while (!token.IsCancellationRequested && await reader.ReadAsync(token)) | |
{ | |
var row = new List<object?>(reader.FieldCount); | |
for (var i = 0; i < reader.FieldCount; i++) | |
{ | |
var value = await reader.IsDBNullAsync(i) ? null : reader.GetValue(i); | |
row.Add(value); | |
} | |
yield return row; | |
} | |
} | |
} | |
finally | |
{ | |
if(wasClosed) | |
{ | |
connection?.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment