如何停止填充DataTable ASP.NET

时间:2017-05-05 13:35:35

标签: c# asp.net datatable

我没有找到任何关于停止填充DataTable的可能性的答案。有没有办法做到这一点?我有来自OleDbDataAdapter的数据,有时我必须等待2分钟,但我想告诉用户停止填充这些数据或者只是等待并继续。

OleDbDataAdapter sqlArchiveData = new OleDbDataAdapter(sql_archive);

DataTable dt = new DataTable();

conn.Open();

sqlArchiveData.Fill(dt);

connProdcc1.Close();

1 个答案:

答案 0 :(得分:0)

似乎您可以通过传递CancellationToken来处理取消DataTable RowChanged event中的填充。下面的示例提取了Backgroundworker,这在ASP.NET中并不是最优的,但应该给你一些想法。

以下MSDN论坛帖子中的示例。

https://social.msdn.microsoft.com/Forums/vstudio/en-US/ad4f5811-a08d-4342-bcf1-368ceac834fc/is-there-any-way-to-cancel-a-dataadapterfill-command-while-its-processing?forum=csharpgeneral

private BackgroundWorker worker;
private DataTable table;

private void button2_Click(object sender, EventArgs e)
{
  if (worker != null)
  {
    worker.CancelAsync();
  }
}

private void button1_Click(object sender, EventArgs e)
{  
  this.worker = new BackgroundWorker();
  worker.WorkerReportsProgress = true;
  worker.WorkerSupportsCancellation = true;

  worker.DoWork += new DoWorkEventHandler(worker_DoWork);
  worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

  worker.RunWorkerAsync();
}

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  MessageBox.Show(this.table.Rows.Count.ToString());
}

[System.Diagnostics.DebuggerStepThrough]
void worker_DoWork(object sender, DoWorkEventArgs e)
{
  this.table = new DataTable();

  using (SqlConnection connection= new SqlConnection())
  using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM table", connection))
  {
    table.RowChanged += new DataRowChangeEventHandler(table_RowChanged); 
    da.Fill(table);        
  }
}

[System.Diagnostics.DebuggerStepThrough]
void table_RowChanged(object sender, DataRowChangeEventArgs e)
{
  if (worker.CancellationPending)
  {
    throw new ApplicationException("Canceled"); // throw a spanner in the works
  }
  Thread.Sleep(5); // Just slow things down for testing
}