Do I have to update to use the new async methods for SqlDataReader?

I am working on a large project that works on .NET 4.0. This structure uses ADO.NET for database calls, and we are currently adding asynchronous API methods. The class SqlCommandhas APM methods SqlCommand.BeginExecuteReader() and SqlCommand.EndExecuteReader(), but SqlDataReaderdoes not have asynchronous implementations.
When it ends SqlCommand.ExecuteReader(), I want to iterate the results with SqlDataReader. Microsoft introduces asynchronous methods for SqlDataReaderin .NET 4.5, so I can not use them in 4.0.

Question . Should we upgrade to use asynchronous ( TAP ) methods SqlDataReader? If so, why?

I searched the web and stackoverflow a lot for answers, but I only seem to find implementations for this. This does not tell me what benefits these new implementations can bring.

Implementing .NET 4.0

Here we use asynchronous methods SqlCommand, but we cannot use new asynchronous methods for SqlDataReader, for example SqlDataReader.ReadAsync().

private Task<IDataReader> ExecuteReaderAsync(IDbCommand dbCommand)
{
    var sqlCommand = CheckIfSqlCommand(dbCommand);
    PrepareExecuteReader(dbCommand);

    return Task<IDataReader>
        .Factory
        .FromAsync(sqlCommand.BeginExecuteReader, sqlCommand.EndExecuteReader, null);
}

private void ReadAll(Task<IDataReader> readerTask)
{
    var reader = readerTask.Result;

    while (reader.Read()) // Should this be asynchronously?
    {
        // Do something
    }
}

public Task<IDataReader> Foo(IDbCommand dbCommand) {
    return ExecuteReaderAsync(dbCommand)
        .ContinueWith(readerTask => ReadAll(readerTask));
}

Implementing .NET 4.5

In .NET 4.5, we can use the async / await keywords, and we can use new asynchronous methods for SqlDataReader, for example SqlDataReader.ReadAsync().

private async Task<SqlDataReader> ExecuteReaderAsync(SqlCommand dbCommand)
{
    PrepareExecuteReader(dbCommand);

    return await dbCommand.ExecuteReaderAsync();
}

private async Task ReadAll(SqlDataReader reader)
{
    while (await reader.ReadAsync()) // Should this be asynchronously?
    {
        // Do something
    }
}

public async Task<IDataReader> Foo(SqlCommand dbCommand)
{
    var reader = await ExecuteReaderAsync(dbCommand);
    await ReadAll(reader);

    return reader;
}
+4
source share
1 answer

, , . , , , .

, , . , , . - , .

, , async DataReader , , . , , . ?

, , API , ORM. , Entity Framework nHibernate .NET . EF6 async, async - ToListAsync(). . .

+2

Source: https://habr.com/ru/post/1529210/


All Articles