简体   繁体   English

填充SqlDataAdapter

[英]Filling SqlDataAdapter

I am running a SQLQuery that takes roughly 45 seconds to run and display results. 我运行的SQLQuery大约需要45秒才能运行并显示结果。 I am using Task<DataSet> to populate two drop downs on my page. 我正在使用Task<DataSet>在页面上填充两个下拉菜单。 Well the 1st drop down populates fine (the query is completed in about 2 seconds), the second it seems that the adapter.Fill(dataSet) is not waiting on the query to complete before it begins to fill the drop down with a null dataset. 好吧,第一个下拉列表可以很好地填充(查询在大约2秒内完成),第二个下拉列表似乎是adapter.Fill(dataSet)在开始使用空数据集填充下拉列表之前没有等待查询完成。 What should I alter so that the code execution halts until the query executes completely? 我应该改变什么,以便代码执行停止直到查询完全执行?

Task.Factory.ContinueWhenAll(new[]
{
  One("Data Source=server;Initial Catalog=db;Integrated Security=True;MultipleActiveResultSets=True"),
  Two("Data Source=server;Initial Catalog=db;Integrated Security=True;MultipleActiveResultSets=True"),
}, tasks =>
{
  try
  {
    this.ddl1.DataSource = tasks[0].Result.Tables[0];
    this.ddl1.DataTextField = "One";
    this.ddl1.DataValueField = "ID";
    this.ddl1.DataBind();
    int indexOfLastItem = this.ddl1.Items.Count - 1;
    this.ddl1.SelectedIndex = indexOfLastItem;
    ddl2.DataSource = tasks[1].Result.Tables[0];
    this.ddl2.DataTextField = "Two";
    this.ddl2.DataValueField = "ID";
    this.ddl2.DataBind();
    this.ddl2.Items.Insert(0, new ListItem(Constants.All, Constants.All));
  }
  catch (Exception exception) { throw exception; }
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

public System.Threading.Tasks.Task<DataSet> One(string databaseConnection)
{
  return FillDS("Select * from activeemployees", databaseConnection);
}
public System.Threading.Tasks.Task<DataSet> Two(string databaseConnection)
{
  return FillDS("Select * from mastersalesdatabase", databaseConnection);
}
public System.Threading.Tasks.Task<DataSet> FillDS(string sqlQuery, string connectionString)
{
  try
  {
    var dataSet = new DataSet();
    using (var adapter = new SqlDataAdapter(sqlQuery, connectionString))
    {
        adapter.Fill(dataSet);
        return dataSet;
    }
  }
  catch (Exception exception) { throw exception; }
}

My query Select * from activeemployees completes in about 2 seconds and populates fine, my query Select * from mastersalesdatabase takes roughly 45 seconds and it seems the code just moves on w/oa delay to let the query execute to completion. 我的查询Select * from activeemployees大约在2秒钟内完成,并且填充良好,我的查询Select * from mastersalesdatabase大约需要45秒,看来代码只是在没有延迟的情况下才能使查询执行完毕。

If you're going to do async to retrieve data into a datatable, it should look more like this: 如果要进行异步操作以将数据检索到数据表中,它应该看起来像这样:

public static async Task<DataTable> GetDataTableAsync(string connectionString, SqlCommand command)
{
    using (var connection = new SqlConnection(connectionString))
    {
        command.Connection = connection;
        await connection.OpenAsync();
        using (var dataReader = await command.ExecuteReaderAsync())
        {
            var dataTable = new DataTable();
            dataTable.Load(dataReader);
            return dataTable;
        }
    }
}

Notice there's no need for a dataset. 请注意,不需要数据集。

Then in WebForms, we have to handle async code differently. 然后在WebForms中,我们必须以不同的方式处理异步代码。

protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(DoWorkAsync));
}

private async Task DoWorkAsync()
{
    ActiveEmployeesDropDownList.DataSource = GetDataTableAsync(databaseConnection, new SqlCommand("select * from activeemployees"));
    ActiveEmployeesDropDownList.DataBind();
}

Notice I renamed the control from ddl1 to ActiveEmployeesDropDownList because ddl1 is a horrible name. 注意,我将控件从ddl1重命名为ActiveEmployeesDropDownList因为ddl1是一个可怕的名称。 Your names should have semantic meaning. 您的名字应具有语义。

You'll need to add the async=true attribute to your page according to MSDN . 根据MSDN ,您需要向页面添加async=true属性。

And you should also fix your query to not take 45 seconds, but that's a separate question entirely. 而且,您还应该将查询时间缩短为不超过45秒,但这完全是一个单独的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM