WPF调度{"因为不同的线程拥有它&QUOT调用线程不能访问该对象;} [英] WPF Dispatcher {"The calling thread cannot access this object because a different thread owns it."}

查看:205
本文介绍了WPF调度{"因为不同的线程拥有它&QUOT调用线程不能访问该对象;}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我需要说I'm小白与WPF和C#。
应用程序:创建曼德尔布罗图片(GUI)
我的调度工程完美这种这种情况:

first I need to say that I´m noob with WPF and C#. Application: Create Mandelbrot Image (GUI) My dispatcher works perfectly this this case:

  private void progressBarRefresh(){

       while ((con.Progress) < 99)
       {
           progressBar1.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
                {
                    progressBar1.Value = con.Progress;
                }
              ));
       }
  }

我得到的消息(标题)特林当用低于code要做到这一点:

I get the Message (Title) when tring to do this with the below code:

bmp = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, stride);

this.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
            {                     
                img.Source = bmp;
                ViewBox.Child = img;  //vllt am schluss
            }
          ));

我将试图解释我的计划是如何工作的。
我创建了一个新的线程(因为GUI不响应)的像素和颜色的计算。在这个线程(方法)I'm使用分派刷新我的视框图像后计算已准备就绪。

I will try to explain how my program works. I created a new Thread (because GUI dont response) for the calculation of the pixels and the colors. In this Thread(Method) I´m using the Dispatcher to Refresh my Image in the ViewBox after the calculations are ready.

当我不把计算在一个单独的线程那么我可以刷新或建立自己的形象。

When I don't put the calculation in a separate Thread then I can refresh or build my Image.

推荐答案

万一你想不同的线程之间共享的对象,然后总是创建UI线程对象。后来,当你要访问的对象,你可以检查是否有访问对象。如果您没有访问权限,再调用与UI线程访问的功能。下面的例子code:

Just in case you want the object to be shared among different threads then always create that object on UI thread. Later when you want to access the object, you can check if you have access to object. If you dont have access, re-invoke the function with UI thread access. example code below:

    private void YourMethod()
    {
        if (Application.Current.Dispatcher.CheckAccess())
        {
            // do whatever you want to do with shared object.
        }
        else
        {
            //Other wise re-invoke the method with UI thread access
            Application.Current.Dispatcher.Invoke(new System.Action(() => YourMethod()));
        }
    }

这篇关于WPF调度{&QUOT;因为不同的线程拥有它&QUOT调用线程不能访问该对象;}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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