WPF/C# Don't block the UI

后端 未结 6 1214
再見小時候
再見小時候 2020-12-20 03:11

I\'ve an existing WPF application, which has several sections. Every section is a UserControl, that implements an interface.

The interface specify two methods:

6条回答
  •  情深已故
    2020-12-20 03:59

    Ok now I'm excited, because I think I may have discovered something on my own...

    So, what you do is this: You create a DispatcherFrame, push that frame onto the Dispatcher, and in the RunWorkerCompleted you set the Continue of the Frame to false.

    This is the code so far:

    public void Function()
    {
        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += TimeConsumingFunction;
        var frame = new DispatcherFrame();
        worker.RunWorkerCompleted += (sender, args) =>
                                         {
                                             frame.Continue = false;
                                         };
        worker.RunWorkerAsync();
        Dispatcher.PushFrame(frame);
    }
    
    private void TimeConsumingFunction(object sender, DoWorkEventArgs doWorkEventArgs)
    {
        Console.WriteLine("Entering");
        for (int i = 0; i < 3; i++)
        {
            Thread.Sleep(1000);
        }
        Console.WriteLine("Exiting");
    }
    
    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        Function();
        Console.WriteLine("Returns");
    }
    

提交回复
热议问题