调用线程无法访问此对象,因为另一个线程拥有它

时间:2011-12-14 09:23:20

标签: c# wpf multithreading

我已经阅读了很多有关此错误的帖子,但我不明白如何在我的解决方案中解决它((我有一个带有一些逻辑的进度条对话框 - 通过ButtonClick从MainFrame调用

void OnBtnClick(object sender, RoutedEventArgs e)
{  
    ProgressDialog dlg = new ProgressDialog("");
    dlg.Closing += new CancelEventHandler(dlg_Closing);
    dlg.Closed += new EventHandler(dlg_Closed);
    //dlg.AutoIncrementInterval = 0;
    LibWrap lwrap = new LibWrap();
    DoWorkEventHandler handler = delegate
    {
        BitmapFrame bf = wrap.engine(BitmapFrame.Create(FXPhotoStudio.App
                                                            .draggedImage),
                                     this.fxPSEditorView); 
    };
    dlg.CurrentLibWrap = lwrap;
    dlg.AutoIncrementInterval = 100;
    dlg.IsCancellingEnabled = true;
    dlg.Owner = Application.Current.MainWindow;
    dlg.RunWorkerThread(0, handler); 
}

此进度条对话框的关闭事件中,同一类(MainFrame)中还有一个处理程序

void dlg_Closed(object sender, EventArgs e)
{
    try
    { 
        mainFrameView.CurrentImage = effectedImage;//!error here!
    }
}

affectedImage是MainFrame的一个字段。它由我的ProgressDialog提供。 我在ProgressDialog.cs中进行了以下操作:

(this.Owner as MainFrame).effectedImage = currentLibVrap.GetEffectedImage;

currentLibVrap已在OnBtnClick中设置 - 见上文 谁能帮我解决这个问题呢?

这是关闭ProgressBarDialog:

的代码
    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      if (!Dispatcher.CheckAccess())
      {
        //run on UI thread
        RunWorkerCompletedEventHandler handler = worker_RunWorkerCompleted;
        Dispatcher.Invoke(DispatcherPriority.SystemIdle, handler, new object[] {sender, e}, null);
        return;
      }

      if (e.Error != null)
      {
        error = e.Error;
      }
      else if (!e.Cancelled)
      {
        //assign result if there was neither exception nor cancel

          (this.Owner as MainWindow).effectedImage = currentLibVrap.GetEffectedImage;//! ok there

        result = e.Result;
      }

  //update UI in case closing the dialog takes a moment
 // progressTimer.Stop();
  progressBar.Value = progressBar.Maximum;
  btnCancel.IsEnabled = false;

  //set the dialog result, which closes the dialog
  DialogResult = error == null && !e.Cancelled;
}

还有工作流程:

/// Launches a worker thread which is intended to perform
/// work while progress is indicated, and displays the dialog
/// modally in order to block the calling thread.
/// </summary>
/// <param name="argument">A custom object which will be
/// submitted in the <see cref="DoWorkEventArgs.Argument"/>
/// property <paramref name="workHandler"/> callback method.</param>
/// <param name="workHandler">A callback method which is
/// being invoked on a background thread in order to perform
/// the work to be performed.</param>


   public bool RunWorkerThread(object argument, DoWorkEventHandler workHandler)
    {
      if (autoIncrementInterval.HasValue)
      {
        //run timer to increment progress bar
        progressTimer.Interval = TimeSpan.FromMilliseconds(autoIncrementInterval.Value);
        progressTimer.Start();
         // LibWrap lwrap = new LibWrap();
         // BitmapFrame bf = lwrap.engine(BitmapFrame.Create(FXPhotoStudio.App.draggedImage));//(aa.Image);

      }

      //store the UI culture
      uiCulture = CultureInfo.CurrentUICulture;

      //store reference to callback handler and launch worker thread
      workerCallback = workHandler;
      worker.RunWorkerAsync(argument);

      //display modal dialog (blocks caller)
      return ShowDialog() ?? false;
    }

/// <summary>
/// Worker method that gets called from a worker thread.
/// Synchronously calls event listeners that may handle
/// the work load.
/// </summary>
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  try
  {
    //make sure the UI culture is properly set on the worker thread
    Thread.CurrentThread.CurrentUICulture = uiCulture;
    //invoke the callback method with the designated argument
    workerCallback(sender, e);
  }
  catch (Exception)
  {
    //disable cancelling and rethrow the exception
    //Dispatcher.BeginInvoke(DispatcherPriority.Normal,
     //                      (SendOrPostCallback) delegate { btnCancel.SetValue(Button.IsEnabledProperty, false); },
    //                       null);
    return;
    //throw;
  }
}

2 个答案:

答案 0 :(得分:1)

你需要使用Dispatcher.BeginInvoke(发送并立即返回)或Dispatcher.Invoke将其发送到UI线程(阻止直到动作被调度)

这是因为,默认情况下,应用程序的线程模型是单线程单元(STA)。这意味着,只有创建了UI元素的线程才能与之交互,其他想要对UI元素做某事的线程必须将对元素的操作分配给UI线程

void dlg_Closed(object sender, EventArgs e)
{
    try
    { 
        mainFrameView.CurrentImage = effectedImage;//!error here!
    }
}

您确定UI线程发送此事件吗?您是否尝试过调度设置CurrentImage? 您能否简化代码并仅保留相关方法?

UPD:我的意思是,您是否尝试过调度CurrentImage设置?

    Application.Current.MainWindow.Dispatcher.BeginInvoke(new Action(()=>
                                          {
                                              mainFrameView.CurrentImage = effectedImage;
                                          }));

答案 1 :(得分:1)

您可以使用Dispather.Invoke或Dispatcher.BeginInvoke。他们都将编组调用UI线程(这就是你的错误),BeginInvoke是为在后台线程中运行繁重的操作而设计的,而Invoke只是一个编组器,所以对于你的任务类型我会坚持最后一个之一。

以下是您的操作方法(假设mainFrameView.CurrentImage属于Image类型,否则只需更改为任何类型):

<强> C#

更新1为参数使用唯一名称,以避免使用现有变量名称进行伪造。

mainFrameView.Dispatcher.Invoke(new Action<object>((myImage2012) => 
{ mainFrameView.CurrentImage = (Image)myImage2012; }), 
new object[1] { effectedImage });