WPF使用BackgroundWorker操作DataTable报错
我在UserControl的Load事件中初始化一个BackgroundWorker,并定义了相关事件,代码如下:
this._bgWorkor = new BackgroundWorker();
this._bgWorkor.WorkerReportsProgress = true;
this._bgWorkor.DoWork += new DoWorkEventHandler(_bgWorkor_DoWork);
this._bgWorkor.ProgressChanged += new ProgressChangedEventHandler(_bgWorkor_ProgressChanged);
this._bgWorkor.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bgWorkor_RunWorkerCompleted);
void _bgWorkor_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage > 0)
{
DataRow dr = (DataRow)e.UserState;
object[] items = new object[dr.ItemArray.Count()];
dr.ItemArray.CopyTo(items, 0);
//执行到下面这一句就提示那个异常错误了
this._DtGuests.Rows.Add(items);
this.spInfo.Content = new TextBlock
{
Text = items[6].ToString(),
Foreground = Brushes.Red,
VerticalAlignment = VerticalAlignment.Center
};
//this.Dispatcher.BeginInvoke(new Action(() =>
//{
//}));
}
}
void _bgWorkor_DoWork(object sender, DoWorkEventArgs e)
{
DataTable dtGuest = (DataTable)e.Argument;
foreach (DataRow dr in dtGuest.Rows)
{
DataRow drNew = this._DtGuests.NewRow();
int result = this._Dao.ExecuteNonQuery(sql, parameters);
((BackgroundWorker)sender).ReportProgress(result, drNew);
}
}