Convert an existing c# synchronous method to asynchronous using async / await?
•
Java
Starting with the synchronous I / O binding method (shown below), how do I use async / await to make it asynchronous?
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;
}
The MSDN examples assume that * async methods exist and do not create a guide for I / O binding operations
I can use task Run() and execute iobound() in the new task, but it is not encouraged to create a new task because the operation is not limited by CPU
I want to use async / await, but I still insist on the basic problem of how to continue to convert this method
Solution
Converting this particular method is simple:
// 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;
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
