【问题标题】:Error:The calling thread cannot access this object because a different thread owns it错误:调用线程无法访问此对象,因为不同的线程拥有它
【发布时间】:2012-10-31 09:45:46
【问题描述】:

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

我用这段代码来显示气球

 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 = 气球;

【问题讨论】:

    标签: c# .net wpf


    【解决方案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”。

    【讨论】:

    • 你到底做了什么?在DisplayFormThread方法里面,你有没有尝试在上面的invoke方法中调用Show()?
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多