异步运行参数化查询/命令?

时间:2017-02-17 16:14:47

标签: c# sql asynchronous

我怎样才能使用以下代码并使myValues的每次迭代异步(关于执行命令,而不是循环本身)?

using (var connection = new SqlConnection(CONNECTION_STRING))
using (var command = new SqlCommand(query, connection))
{
    connection.Open();
    command.Parameters.Add("@myParameter", SqlDbType.VarChar)
    foreach(string myValue in myValues)
    {
        command.Parameters["@myParameter"].Value = myValue;
        using (var dr = command.ExecuteReader(CommandBehavior.SingleResult))
        {
            while (dr.Read())
            {
                //do something
            }
        }
    }   
}

1 个答案:

答案 0 :(得分:0)

这是你需要的吗?

private void MyMethod()
{
    UpdateValues();
}

async Task UpdateValues()
{
    using (var connection = new SqlConnection("your_connection_string_here"))
    {
        using (var command = new SqlCommand("your_sql_statement_here", connection))
        {
            await connection.OpenAsync();
            command.Parameters.Add("@myParameter", SqlDbType.VarChar);

            foreach (string myValue in myValues)
            {
                command.Parameters["@myParameter"].Value = myValue;

                var dr = await command.ExecuteReaderAsync(CommandBehavior.SingleResult);
                while (await dr.ReadAsync())
                {
                    // do your thing here //
                }
            }
        }
    }
}