Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert existing C# synchronous method to asynchronous with async/await?

Starting with a synchronous I/O bound method (below), how do I make it asynchronous using async/await?

public int Iobound(SqlConnection conn, SqlTransaction tran)
{
    // this stored procedure takes a few seconds to complete
    SqlCommand cmd = new SqlCommand("MyIoboundStoredProc", conn, tran);
    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter returnValue = cmd.Parameters.Add("ReturnValue", SqlDbType.Int);
    returnValue.Direction = ParameterDirection.ReturnValue;
    cmd.ExecuteNonQuery();

    return (int)returnValue.Value;
}

MSDN examples all presume the preexistence of an *Async method and offer no guidance for making one yourself for I/O-bound operations.

I could use Task.Run() and execute Iobound() within that new Task, but new Task creation is discouraged since the operation is not CPU-bound.

I'd like to use async/await but I'm stuck here on this fundamental problem of how to proceed with the conversion of this method.

like image 274
MikeZ Avatar asked Mar 08 '23 12:03

MikeZ


1 Answers

Conversion of this particular method is pretty straight-forward:

// change return type to Task<int>
public async Task<int> Iobound(SqlConnection conn, SqlTransaction tran) 
{
    // this stored procedure takes a few seconds to complete
    using (SqlCommand cmd = new SqlCommand("MyIoboundStoredProc", conn, tran)) 
    {
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter returnValue = cmd.Parameters.Add("ReturnValue", SqlDbType.Int);
        returnValue.Direction = ParameterDirection.ReturnValue;
        // use async IO method and await it
        await cmd.ExecuteNonQueryAsync();
        return (int) returnValue.Value;
    }
}
like image 152
Evk Avatar answered Mar 10 '23 00:03

Evk