调用线程无法访问此对象

本文关键字:对象 访问 线程 调用 | 更新日期: 2023-09-27 18:26:55

我正在尝试创建一个计时器,它将返回到我的WPF应用程序的主菜单,比如说,30秒的不活动状态。但我得到了错误"调用线程无法访问此对象,因为另一个线程拥有它。"并且它发生在storyboard.Begin(uc);FadeOut()

我已经看到了一些涉及调用调度器的解决方案,但我不确定如何在我的案例中应用?

public void ResetScreen()
{
    if (!mainScreen)
    {
        Timer myTimer = new Timer();
        myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        myTimer.Interval = 1000;
        myTimer.Start();
    }
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    TransitionContent(oldScreen, newScreen);
}
private void FadeIn(FrameworkElement uc)
{
    DoubleAnimation dAnimation = new DoubleAnimation();
    dAnimation.Duration = new Duration(TimeSpan.FromSeconds(1.0));
    dAnimation.From = 0;
    dAnimation.To = 1;
    Storyboard.SetTarget(dAnimation, uc);
    Storyboard.SetTargetProperty(dAnimation, new PropertyPath(OpacityProperty));
    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(dAnimation);
    storyboard.Begin(uc);
}
private void FadeOut(FrameworkElement uc)
{
    DoubleAnimation dAnimation = new DoubleAnimation();
    dAnimation.Duration = new Duration(TimeSpan.FromSeconds(1.0));
    dAnimation.From = 1;
    dAnimation.To = 0;
    Storyboard.SetTarget(dAnimation, uc);
    Storyboard.SetTargetProperty(dAnimation, new PropertyPath(OpacityProperty));
    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(dAnimation);
    storyboard.Begin(uc);
}
private void TransitionContent(FrameworkElement oldScreen, FrameworkElement newScreen)
{
    FadeOut(oldScreen);
    FadeIn(newScreen);
}

调用线程无法访问此对象

这可能是一个解决方案:

this.Dispatcher.Invoke((Action)(()=>{
      // In here, try to call the stuff which making some changes on the UI
});

例如:

private void TransitionContent(FrameworkElement oldScreen, FrameworkElement newScreen)
{
     this.Dispatcher.Invoke((Action)(()=>{
          FadeOut(oldScreen);
          FadeIn(newScreen);   
     });
}

您的问题是System.Timers.Timer事件在不同于UI线程的线程上运行。您可以尝试像其他人提到的那样直接调用,也可以使用DispatcherTimer。