使用async/await将现有的C#同步方法转换为异步方法? [英] Convert existing C# synchronous method to asynchronous with async/await?
问题描述
从同步I/O绑定方法(如下)开始,如何使用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示例都假定存在* Async方法,并且没有为使自己从事I/O绑定操作提供任何指导.
MSDN examples all presume the preexistence of an *Async method and offer no guidance for making one yourself for I/O-bound operations.
我可以在新任务中使用Task.Run()并执行Iobound(),但是不鼓励创建新的Task,因为该操作不受CPU限制.
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.
我想使用async/await,但是在这个基本问题上,我仍然停留在这里,该问题是如何进行此方法的转换的.
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.
推荐答案
此特定方法的转换非常简单:
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;
}
}
这篇关于使用async/await将现有的C#同步方法转换为异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!