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

时间:2012-10-31 09:45:46

标签: c# .net wpf

我有一个Threading.timer,在特殊的时间显示一个气球。

我将此代码用于show Balloon

 var thread = new Thread(new ThreadStart(DisplayFormThread));

        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();

 private void DisplayFormThread()
{
    try
    {
        Show();
    }
    catch (Exception ex)
    {
        //  Log.Write(ex);
    }
}

这是我的节目气球班。

 if (!Application.Current.Dispatcher.CheckAccess())
    {
        var action = new Action(() => ShowCustomBalloon(balloon, animation, timeout));
        Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, action);
        return;
    }

    if (balloon == null) throw new ArgumentNullException("balloon");
    if (timeout.HasValue && timeout < 500)
    {
        string msg = "Invalid timeout of {0} milliseconds. Timeout must be at least 500 ms";
        msg = String.Format(msg, timeout);
        throw new ArgumentOutOfRangeException("timeout", msg);
    }

    Popup popup = new Popup();
    popup.AllowsTransparency = true;
    popup.PopupAnimation = animation;
    popup.Child = balloon;
    popup.Placement = PlacementMode.AbsolutePoint;
    popup.StaysOpen = true;

    Point position = new Point(SystemParameters.WorkArea.Width - ((UserControl)balloon).Width,
             SystemParameters.WorkArea.Height - ((UserControl)balloon).Height);
    popup.HorizontalOffset = position.X - 1;
    popup.VerticalOffset = position.Y - 1;
    //display item
    popup.IsOpen = true;

当我显示气球时我得到错误:调用线程无法访问此对象,因为另一个线程拥有它

在这段代码中我得到错误:

  

popup.Child = balloon;

1 个答案:

答案 0 :(得分:1)

您无法直接从其他线程更新UI。当您在线程中完成并需要更新UI时,您可以使用以下内容:

this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
    // Update UI properties
});

“this”是一个UI元素,例如窗口。您也可以使用:

System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
    // Update UI properties
});

而不是引用UI组件,即上例中的“this”。