后台工作使我的应用程序挂起

本文关键字:应用程序 挂起 我的 工作 后台 | 更新日期: 2023-09-27 18:01:16

我正在使用一个后台工作器,它从数据库中取出下一个100条记录,并在运行时将其绑定到网格。它工作得很好,但我的应用程序挂起,虽然网格显示正确。出于同样的目的,我正在为所有其他屏幕使用后台工作器。如果我打开任何一个屏幕,它会挂起。

我也经历过这种情况,但无济于事。

这是我的代码DoWork事件处理程序。

while (bgStop)
 {
     e.Result = addNewRecords();
     if (Convert.ToBoolean(e.Result) == false)
     {
         e.Cancel = true;
         backgroundWorker1.WorkerSupportsCancellation = true;
         bgStop = false;
         killBGWorker();
     } 
 }

addNewRecords我合并数据表到数据源的网格

后台工作使我的应用程序挂起

如果您发布了一些代码或它抛出的异常,那么跟踪将是有益的。

然而,我猜你可能试图在非UI线程中更新你的UI相关活动,或者你可能正在做一些不安全的事情。

简单地说,将与数据库相关的读操作放在DoWorkEventHandler中,将与UI相关的操作放在RunWorkerCompletedEventHandler中。您还可以在更新UI控件之前检查线程关联。

你不能与来自后台工作线程的ui线程交互。然而,你可以使用委托来更新你的UI-control。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    UpdateDataGridView();
}
delegate void UpdateDataGridViewDelegate(string args);
private void UpdateDataGridView(string args)
{
   if (dataGridView.InvokeRequired)
       dataGridView.Invoke(new UpdateDataGridViewDelegate(UpdateDataGridView), args);
   else
    {
        //update datagridview
    }
}

检查worker中是否存在无限循环。