且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用async/await将现有的C#同步方法转换为异步方法?

更新时间:2022-01-03 08:28:23

此特定方法的转换非常简单:

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;
    }
}