WPF:异步进度条 [英] WPF: Asynchronous progress bar

查看:837
本文介绍了WPF:异步进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创造一个进度条,将异步工作的主要过程。我创建了一个新的事件,并调用它每次不过后来我尝试进度条我收到以下错误执行操作:

I'm trying to create a progress bar that will work asynchronously to the main process. I'm created a new event and invoked it however everytime I then try to perform operations on the progress bar I recieve the following error:

,因为不同的线程拥有它调用线程不能访问该对象

"The calling thread cannot access this object because a different thread owns it"

以下code是发送进度条事件为对象的实例的尝试,它显然失败了,但它给你什么样的code看起来像一个想法。

The following code is an attempt to send an instance of the progress bar to the event as an object, it obviously failed but it gives you an idea of what the code looks like.

    private event EventHandler importing;

    void MdbDataImport_importing(object sender, EventArgs e)
    {
        ProgressBar pb = (ProgressBar)sender;
        while (true)
        {
            if (pb.Value >= 200)
                pb.Value = 0;

            pb.Value += 10;
        }
    }

    private void btnImport_Click(object sender, RoutedEventArgs e)
    {
        importing += new EventHandler(MdbDataImport_importing);
        IAsyncResult aResult = null;

        aResult = importing.BeginInvoke(pbDataImport, null, null, null);

        importing.EndInvoke(aResult);
    }

有没有人有想法如何做到这一点。

Does anyone have ideas of how to do this.

在此先感谢
SumGuy。

Thanks in advance SumGuy.

推荐答案

您应该使用类似这样

pb.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate()
                    {

                        if (pb.Value >= 200)
                            pb.Value = 0;

                        pb.Value += 10;
                    }
                ));

在while循环

这篇关于WPF:异步进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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