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

从同步I / O绑定方法开始(如下所示),如何使用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示例都假设存在* Async方法,并且没有为I / O绑定操作自己创建一个指导.

我可以使用Task.Run()并在该新任务中执行Iobound(),但不鼓励创建新任务,因为该操作不受cpu限制.

我想使用async / await,但我仍然坚持这个如何继续转换此方法的基本问题.

解决方法

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

// 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",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;
    }
}

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...