且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF / C#不要阻塞UI

更新时间:2023-01-23 18:16:15

好了,现在我很兴奋,因为我想我可能已经发现了一些我自己的......

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

所以,你做什么,是这样的:你创建一个DispatcherFrame,推动该帧到调度员,并在RunWorkerCompleted您设置的继续帧为false

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.

这是在code到目前为止:

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