Reputation: 5002
I have a Threading.timer that show a ballon in a special time.
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;
Upvotes: 0
Views: 581
Reputation: 1837
You cannot update UI directly from another thread. When you are done in the thread and need to update the UI then you can use following:
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
// Update UI properties
});
"this" is a UI element for example the window. 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 i.e. "this" in the example above.
Upvotes: 1