[英]Error:The calling thread cannot access this object because a different thread owns it
I have a Threading.timer that show a ballon in a special time. 我有一个Threading.timer,它在特定时间显示气球。
I use this code for 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);
}
}
it is my class for show ballon . 这是我的表演气球班。
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;
when i show the balloon i get error : The calling thread cannot access this object because a different thread owns it 当我显示气球时,出现错误: 调用线程无法访问该对象,因为其他线程拥有它
in this code i get error : 在这段代码中我得到错误:
popup.Child = balloon; popup.Child =气球;
You cannot update UI directly from another thread. 您不能直接从另一个线程更新UI。 When you are done in the thread and need to update the UI then you can use following: 当您完成线程操作并需要更新UI时,可以使用以下命令:
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
// Update UI properties
});
"this" is a UI element for example the window. “ this”是一个UI元素,例如窗口。 You can also use: 您还可以使用:
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
// Update UI properties
});
instead of reference to the UI component ie "this" in the example above. 而不是引用上面示例中的UI组件(即“ this”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.