Csharp/C#教程:使用async / await将现有C#同步方法转换为异步?分享


使用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,但我仍然坚持这个如何继续转换此方法的基本问题。

转换这种特殊方法非常简单:

上述就是C#学习教程:使用async / await将现有C#同步方法转换为异步?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 // change return type to Task public async Task 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; } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1016665.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐