本文介绍了如何在我的应用程序中使用BackgroundWorker线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi Every Body。

我有一个用户控件的CircularProgressBar。我创建一个名为Printer的窗口并添加CircularProgressBar。

在我的应用中我将当我连接到Sql并加载数据时,将显示CircularProgressBar并且当此加载完成时它将消失。

然后我使用BackgroundWorker线程获取此Mean.this是我的代码:

在公共场所

Hi Every Body.
I Have CircularProgressBar that is a User Control.I Create a Window with Name Of Printer And Add CircularProgressBar to it.
In my App I will When I connect to Sql And Load Data CircularProgressBar is shown And when this Loading finished it disappear.
then I use BackgroundWorker thread for this Mean.this is my code:
in public

Printer p = new Printer();
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);



点击按钮视图时:


When Button View Clicked:

private void View_Click(object sender, RoutedEventArgs e)
      {
           bw.RunWorkerAsync();

      }
  private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
          p.Close();
      }

      private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
      }

      private void bw_DoWork(object sender, DoWorkEventArgs e)
      {
          Dispatcher.BeginInvoke(new Action(() =>
          {
              p.Show();
              ViewTabelsData();
          }));
      }



但是它无法正常工作。



按钮视图首先单击CircularProgressBar显示几秒钟(比它必须显示的更少)然后消失。当按下第二次按钮视图时我得到此异常:System.InvalidOperationException无法设置可见性或调用Show,ShowDialog或WindowInteropHelper.EnsureHandle窗户关闭后。





我的Bug在哪里?我最好的办法是什么?


But It Do not work Correctly.

When Button View first clicked CircularProgressBar just for few seconds shown (that more less than it must shown)and then disappear.when button view for second time pressed I get this Exception: System.InvalidOperationException "Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed."


Where is my Bug?What the best way I do it?

推荐答案

Dispatcher.BeginInvoke(new Action(() =>



with


with

Dispatcher.Invoke(new Action(() =>





它可以帮助您立即关闭表单。 />


要修复InvalidOperationException,每次要显示时都应创建新的Printer实例,或者使用隐藏方法而不是关闭。 />


但总的来说,在bw.DoWork方法中显示你的from并不是一个好主意,更好的地方就在bw.RunWorkerAsync()之前;方法调用。



It should help you with instant form closing.

And to fix InvalidOperationException you should create new instance of Printer every time when you want to show it, or use Hide method instead of close.

But in general it''s not realy a good idea to show your from in bw_DoWork method, better place is right before bw.RunWorkerAsync(); method call.


这篇关于如何在我的应用程序中使用BackgroundWorker线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 12:56