簡體   English   中英

使用async / await將現有C#同步方法轉換為異步?

[英]Convert existing C# synchronous method to asynchronous with async/await?

從同步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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM