Search code examples
.net-coredapper

Asynchronus methods in .net core api


I am using Dapper to connect .net core api with Oracle DB.I have the following methods.

public IDbConnection GetConnection()
    {
        var connectionString = configuration.GetSection("ConnectionStrings").GetSection("AsyncDB").Value;
        var conn = new OracleConnection(connectionString);
        return conn;
    }

public Object GetProducts()
    {
        //throw new System.NotImplementedException();
        object result = null;
        try
        {
            OracleDynamicParameters dynamicParameters = new OracleDynamicParameters();
            dynamicParameters.Add("EMPCURSOR", OracleDbType.RefCursor, ParameterDirection.Output);

            var conn = this.GetConnection();
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }

            if (conn.State == ConnectionState.Open)
            {
                var query = "SPGETPRODUCTINFO";
                result = SqlMapper.Query(conn, query, param: dynamicParameters, commandType: CommandType.StoredProcedure);
            }
        }
        catch (Exception e)
        {
            throw e;
        }

        return result;
    }

The procedure SPGETPRODUCTINFO return rows from the database.

What are the ways to turn the method into asynchronus method using async/await keywords?


Solution

  • First of all, your method is needed to be converted to Async

    public Object GetProducts()
    

    to

    public async Task<Object> GetProductsAsync();
    public async Task<Object> GetProductsAsync(CancellationToken cancellationToken = default(CancellationToken));
    

    If a method supports Async implementation, general conventions shows that method name ends with Async keyword.

    You can check methods whether they have Async Implementation. For Example, if SqlMapper.Query has Async Implementation, it is generally like SqlMapper.QueryAsync.

    Futhermore Async Implementations has return type Task. in order to handle Async Implementation you can do this

    result = await SqlMapper.QueryAsync(conn, query, param: dynamicParameters, commandType: CommandType.StoredProcedure);
    

    Also, If you want your Method supports Cancellation, then you need to have CancellationToken cancellationToken = default(CancellationToken) as parameter and your method will be

    result = await SqlMapper.QueryAsync(conn, query, param: dynamicParameters, commandType: CommandType.StoredProcedure, cancellationToken: cancellationToken);