在长时间运行的操作之前强制重绘 [英] Force redraw before long running operations

查看:35
本文介绍了在长时间运行的操作之前强制重绘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您有一个按钮时,请执行以下操作:

When you have a button, and do something like:

Private Function Button_OnClick

    Button.Enabled = False

    [LONG OPERATION] 

End Function

那么按钮就不会变灰了,因为长时间的操作会阻止UI线程重新绘制控件.我知道正确的设计是启动后台线程/调度程序,但有时这对于简单的操作来说太麻烦了.

Then the button will not be grayed, because the long operation prevents the UI thread from repainting the control. I know the right design is to start a background thread / dispatcher, but sometimes that's too much hassle for a simple operation.

那么如何强制按钮在禁用状态下重绘?我在 Button 上尝试了 .UpdateLayout(),但没有任何效果.我也试过 System.Windows.Forms.DoEvents() ,它在使用 WinForms 时正常工作,但它也没有效果.

So how do I force the button to redraw in disabled state? I tried .UpdateLayout() on the Button, but it didn't have any effects. I also tried System.Windows.Forms.DoEvents() which normally works when using WinForms, but it also had no effect.

推荐答案

以下代码将满足您的需求.但是我不会使用它.使用 BackgroundWorker 类进行长时间操作.它易于使用且非常稳定.
代码如下:

The following code will do what you're looking for. However I would not use it. Use the BackgroundWorker class for long time operations. It's easy to use and very stable.
Here the code:

   public static void ProcessUITasks() {            
        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(object parameter) {
            frame.Continue = false;
            return null;
        }), null);
        Dispatcher.PushFrame(frame);
    }

此处您会找到有关如何使用 BackgroundWorker.

Here you will find a sample on how to use the BackgroundWorker.

这篇关于在长时间运行的操作之前强制重绘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆