【问题标题】:The calling thread cannot access this object调用线程无法访问此对象
【发布时间】:2012-03-22 12:52:35
【问题描述】:

我正在尝试创建一个计时器,它可以返回到我的 WPF 应用程序的主菜单,比如 30 秒不活动。但我收到错误“调用线程无法访问此对象,因为不同的线程拥有它。”它发生在FadeOut()storyboard.Begin(uc);

我见过一些涉及调用调度程序的解决方案,但我不确定如何在我的情况下应用?

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);
}

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    这可能是一个解决方案:

    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);   
         });
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-31
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        相关资源
        最近更新 更多