简体   繁体   English

重新启动BackgroundWorker C#和WPF

[英]Restart a BackgroundWorker C# and WPF

I read this guide about the BackgroundWorker class. 我阅读了有关BackgroundWorker类的指南

I am trying to implement a reset button, so I added following code. 我正在尝试实现一个重置按钮,因此添加了以下代码。

In Page.xaml : Page.xaml中

<Button x:Name="buttonReset" Content="Reset" Click="buttonReset_Click"
                    Width="80" Height="30"/>

and in Page.cs : 并在Page.cs中

    private void buttonReset_Click(object sender, RoutedEventArgs e)
    {
        if (bw.WorkerSupportsCancellation == true)
        {
            bw.CancelAsync();
        }

        // How to restart?

        bw.RunWorkerAsync(); // Raises busy exception

    }

But I get following error: 但是我得到以下错误:

在此处输入图片说明

From italian: 来自意大利语:

This BackgroundWorker is busy and couldn't execute more than one task in the same time 这个BackgroundWorker很忙,无法同时执行多个任务

This exactly occurs only when I press Start a then Reset . 仅当我按“ 开始” 然后“ 重置”时,这才发生。

Why? 为什么? And how to fix? 以及如何解决?

Please note that this is a bad solution even if works 请注意,即使可行,这也是一个不好的解决方案

I tried this: 我尝试了这个:

    private void buttonReset_Click(object sender, RoutedEventArgs e)
    {
        if (bw.WorkerSupportsCancellation == true)
        {
            bw.CancelAsync();

            while (bw.IsBusy)
            {
                DoEvents();
            }
        }

        bw.RunWorkerAsync();

    }

    public static void DoEvents()
    {
        Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
                                              new Action(delegate { }));
    }

This solved the problem. 这样就解决了问题。

In particular i added: 特别是我补充说:

     while (bw.IsBusy)
     {
          DoEvents();
     }

where DoEvents() is defined: 在其中定义了DoEvents()

    public static void DoEvents()
    {
        Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
                                              new Action(delegate { }));
    }

as mentioned ( here ). 如所提到的( 这里 )。

Note: special thanks to a mysterious user who replied here but deleted his answer. 注意:特别感谢一位神秘用户在这里回答但删除了他的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM