从同步 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", 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)