【问题标题】:C# Timer thread crash, BeginInvokeC# Timer 线程崩溃,BeginInvoke
【发布时间】:2013-09-24 15:39:40
【问题描述】:

我有一个“animateMyWindow”类,可以使用 Timer 更改打开窗口的不透明度。

    namespace POCentury
{
    class animateMyWindow
    {
        Timer _timer1 = new Timer();
        Window _openedWindow = null;
        public void animationTimerStart(object openedWindow)
        {
            if (openedWindow == null)
            {
                throw new Exception("Hata");
            }
            else
            {
                _openedWindow = (Window)openedWindow;
                _timer1.Interval = 1 * 25;
                _timer1.Elapsed +=  new ElapsedEventHandler(animationStart);
                _timer1.AutoReset = true;
                _timer1.Enabled = true;
                _timer1.Start();
            }
        }
        private void animationStart(object sender, ElapsedEventArgs e)
        {
            if (_openedWindow.Opacity == 1)
                animationStop();
            else
                _openedWindow.Opacity += .1;
        }
        private void animationStop()
        {
            _timer1.Stop();
        }
    }
}

animationStart 函数无法访问我的窗口,因为它正在另一个线程上工作。 我已经尝试过 Dispatcher.BeginInvoke 并且无法使其工作。 你能帮我做吗?

【问题讨论】:

  • 如果这是 WPF 你应该检查codeproject.com/Articles/23257/…WPF中有一些不错的动画工具
  • 如果您使用 DispatcherTimer,您将避免使用 Dispatcher。更简单的是完全放弃计时器的东西并通过DoubleAnimation为不透明度设置动画。
  • 谢谢@Clemens,它现在正在使用 DispatcherTimer。

标签: c# wpf window opacity


【解决方案1】:

基本上,您无法在animationStart 事件中访问openedWindow,因为它发生在不同的线程中。您需要 Dispatcher 来执行此操作。

Dispatcher.BeginInvoke(new Action(() =>
{
        if (_openedWindow.Opacity == 1)
                animationStop();
            else
                _openedWindow.Opacity += .1;
}));

【讨论】:

  • Dispatcher.BeginInvoke 不工作。它给出“错误 1 ​​非静态字段、方法或属性需要对象引用..”
  • 试试Dispatcher.CurrentDispatcher.BeginInvoke(...)
  • 我可以回答这个问题,但您几乎提供了完整的解决方案。如果将 Dispatcher.BeginInvoke 替换为 _openedWindow.Dispatcher.BeginInvoke,您将调用正确的调度程序。他在 Class Dispatcher 和 Window 的属性 Dispatcher 之间有问题
  • @Magnus Grindal Bakken:如果他在另一个线程上会出错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
相关资源
最近更新 更多