17

首先我需要说我是 WPF 和 C# 的菜鸟。应用程序:创建 Mandelbrot 图像 (GUI) 我的调度程序在这种情况下工作得很好:

  private void progressBarRefresh(){

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

尝试使用以下代码执行此操作时,我收到消息(标题):

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 不响应)来计算像素和颜色。在这个线程(方法)中,计算准备好后,我正在使用调度程序刷新 ViewBox 中的图像。

当我不将计算放在单独的线程中时,我可以刷新或构建我的图像。

4

5 回答 5

33

万一您希望在不同线程之间共享对象,则始终在 UI 线程上创建该对象。稍后当您想访问该对象时,您可以检查您是否有权访问该对象。如果您没有访问权限,请使用 UI 线程访问权限重新调用该函数。下面的示例代码:

    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()));
        }
    }
于 2012-12-05T15:14:32.657 回答
7

MSDN 说:“冻结的 Freezable 可以跨线程共享。”

也许这个线程会有所帮助:http ://social.msdn.microsoft.com/Forums/en-US/windowswic/thread/9223743a-e9ae-4301-b8a4-96dc2335b686

于 2010-06-05T23:30:45.457 回答
3

当你得到一个时,Dispatcher你会为每个不同的线程得到一个不同的。

this.Dispatcher可能会给您另一个调度程序而不是 UI 调度程序,因此您会收到该错误。

尝试Application.Current.Dispatcher改用,这将始终返回 UI 线程的 Dispatcher。

当然,如果您Dispatcher.CurrentDispatcher从另一个线程使用,可能会发生同样的错误。

于 2013-01-28T21:11:57.937 回答
2

您还可以使用队列机制在线程之间传递消息。毕竟,这就是 Windows 体系结构的工作方式。这就是调度员正在做的事情。您正在将引用传递给不属于 WPF 线程的委托。

所以是的,你有基本的想法,但你需要通过使用将位图实际传递给另一个线程Action<T>(T object),或者在你的情况下:

Dispatcher.Invoke(DispatcherPriority.Send, new Action<Bitmap>(delegate(Bitmap img) {
    do things here...
}), bmp);
于 2010-06-05T23:51:21.583 回答
2

您正在bmp您的工作线程(?)上创建位图(),然后将其传递给 UI 线程——这就是失败的原因。

您需要在 UI 线程上创建图像。您可能需要某种方式来引用要显示的图像并将信息传递给 UI。

于 2010-06-05T23:26:16.460 回答