簡體   English   中英

重新啟動BackgroundWorker C#和WPF

[英]Restart a BackgroundWorker C# and WPF

我閱讀了有關BackgroundWorker類的指南

我正在嘗試實現一個重置按鈕,因此添加了以下代碼。

Page.xaml中

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

並在Page.cs中

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

        // How to restart?

        bw.RunWorkerAsync(); // Raises busy exception

    }

但是我得到以下錯誤:

在此處輸入圖片說明

來自意大利語:

這個BackgroundWorker很忙,無法同時執行多個任務

僅當我按“ 開始” 然后“ 重置”時,這才發生。

為什么? 以及如何解決?

請注意,即使可行,這也是一個不好的解決方案

我嘗試了這個:

    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 { }));
    }

這樣就解決了問題。

特別是我補充說:

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

在其中定義了DoEvents()

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

如所提到的( 這里 )。

注意:特別感謝一位神秘用戶在這里回答但刪除了他的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM