1

The Problem

I'm trying to play a StoryBoard from a different thread but a 'System.InvalidOperationException' is thrown in WindowsBase.dll.

I have a custom Control, InfoBar, which has a StoryBoard to close it and a System.Timers.Timer object to do so after several seconds.

So, how do I call BeginStoryboard() from a different thread?

Error Message

The exception thrown on BeginStoryboard(sb):

An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code

Additional information: The calling thread cannot access this object because a different thread owns it.

My (simplified) Code

private int TimerSeconds;
private System.Timers.Timer t;

public InfoBar()
{
    this.InitializeComponent();
    TimerSeconds = 0;
    t = new System.Timers.Timer(1000);
    t.Elapsed += t_Elapsed;
}

void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    if(TimerSeconds==3)
    {
        t.Stop();
        TimerSeconds = 0;    
        System.Windows.Media.Animation.Storyboard sb = (System.Windows.Media.Animation.Storyboard)FindResource("sbClose");
        BeginStoryboard(sb);    
    }
    else
    {
        TimerSeconds++;
    }
}
4

1 回答 1

2

将委托放在 UI调度程序上,它会自动将您的东西放入 UI 线程。您只能在 UI 线程上执行 UI 操作。

App.Current.Dispatcher.Invoke((Action)delegate
{
      System.Windows.Media.Animation.Storyboard sb =
            (System.Windows.Media.Animation.Storyboard)FindResource("sbClose");
      BeginStoryboard(sb);
});
于 2013-08-21T19:56:02.120 回答