gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:06:29 24 4
gpt4 key购买 nike

从同步 I/O 绑定(bind)方法(下文)开始,如何使用 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 绑定(bind)操作自行制作方法的指导。

我可以在该新任务中使用 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;
}
}

关于c# - 使用 async/await 将现有的 C# 同步方法转换为异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47500244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com