I want to refactor this Method into an Asynchronous Task

Tom Meier 220 Reputation points
2024-03-25T15:51:51.8733333+00:00

I would like to refactor the below method that's loading a Model to be Asynchronous. I'm new to Asynchronous Tasks and would appreciatiate any guidance. Thanks !

public List<T> LoadData<T,U>(string sqlStatement, U parameters, string connectionString)

{

using IDbConnection connection=new SQLiteConnection(connectionString)

List<T> rows=connection.Query<T>(sqlStatement, parameters).ToList();

return rows;

}

var output=_db.LoadData<PayerListModel, dynamic>(sql, new {Filter=$"%{filter}%"}, connString);

return output;

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,647 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,496 Reputation points
    2024-03-25T16:03:48.8466667+00:00
    public async Task<List<T>> LoadDataAsync<T, U>(string sqlStatement, U parameters, string connectionString) {
    	using IDbConnection connection = new SqliteConnection(connectionString);
    
    	IEnumerable<T> rows = await connection.QueryAsync<T>(sqlStatement, parameters);
    
    	return rows.ToList();
    }
    
    var output = await _db.LoadDataAsync<PayerListModel, dynamic>(sql, new { Filter = $"%{filter}%" }, connString);
    
    return output;
    

    The first thing you'll want to do is use the QueryAsync variant of the Query method provided by Dapper, which will return a Task<IEnumerable<T>> instead of IEnumerable<T>.

    Also as LoadData needs to await the response of this in order to .ToList() it you'll need to mark the method as async. Just for completion I've just renamed LoadData to LoadDataAsync, which is the convention used when you have a Task<...> returning method.

    0 comments No comments

0 additional answers

Sort by: Most helpful