BackgroundWorker无法正确访问表单 [英] BackgroundWorker not accessing correctly a form

查看:104
本文介绍了BackgroundWorker无法正确访问表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我在C#中有一个使用backgroundWorker进行计算的应用程序.由BackgroundWorker执行的当前操作在ListBox中显示给主线程创建的Form.当backgroundWorker完成工作后,该表单将保持打开状态,直到用户关闭它为止.问题是backgroundWorker第一次启动可以正常工作,但是第二次没有执行它的工作(没有将东西放到ListBox中并且没有执行该操作).但是,如果我在backgroundWorker_DoWork()中放置一个断点并逐步进行,则可以正常工作.有人可以给我一些帮助吗?

这是调用backgroundWorker
方法的一部分

Hello,
I have an application in C# that uses a backgroundWorker to make some calculations. The current operation performed by the backgroundWorker is displayed to a Form that is created by the main thread, in a ListBox. When the backgroundWorker has finished it''s work the form remains open until the user closes it. The problem is that the first time that the backgroundWorker starts it works fine, but the second time is not doing it''s job(not putting stuff in the ListBox and not performing the operation). But, if I put a breakpoint in the backgroundWorker_DoWork() and go step by step it works fine. Can someone give me some help with this?

This is the part of the method that calls the backgroundWorker

 if (workYourBack.IsBusy == true)
 {
     try
     {
         workYourBack.CancelAsync();

     }
     catch(System.InvalidOperationException ex)
     {
         MessageBox.Show("No se puede lanzar.");
         return;
     }
 }


 try
 {
     _sW.Close();
 }
 catch (System.InvalidOperationException ex)
 {
     MessageBox.Show("Invalid operation.");
     return;
 }
 catch (System.NullReferenceException ex1)
 {

 }


 _sW = new StatusWindow();
 workYourBack.RunWorkerAsync(mlParam);
_sW.ShowDialog();



backgroundWorker.DoWork()



backgroundWorker.DoWork()

           _sW.Invoke((MethodInvoker)delegate()
           {
               if (_sW.Visible == false)
               _sW.ShowDialog();
           });
          _sW.Invoke((MethodInvoker)delegate()
          {
              _sW.InsertText("<<<OBTENER INFORMACIÓN DEL CENTRO>>>");
              _sW.InsertText("Procesando capas.......");
          }
    
          //work to be done and various calls to _sW.Invoke

         

);


谢谢.

推荐答案

我认为您的问题可能与从外部以及可能在工作线程内部调用ShowDialog有关.我建议您在Form_Load中创建工作,然后从外部调用ShowDialog.

I think your problem maybe to do with calling ShowDialog from outside and potentially inside the worker thread. I suggest you create you work in Form_Load then call ShowDialog from outside.

if (_sW.Visible == false)
              _sW.ShowDialog();


如果显示了表单但看不到该表单,请像这样


if the form is shown but not visible make it visible like this

if (_sW.Visible == false)
              _sW.Visible = true;


这篇关于BackgroundWorker无法正确访问表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆