代码之家  ›  专栏  ›  技术社区  ›  Hotkey

启用值为true的计时器在WinFormAnimation中使用时不起作用

  •  1
  • Hotkey  · 技术社区  · 5 年前

    我正在尝试使System.Windows.Forms.Timer在动画后工作。

    private Timer timer1 = new Timer();
    
    protected override void OnLoad(EventArgs e)
    {
        timer1.Interval = 25;
        timer1.Tick += timer1_Tick;
    
        tempX = this.Location.X;
        new Animator2D(new Path2D(-300, 23, this.Location.Y, this.Location.Y, 1500, AnimationFunctions.ExponentialEaseOut))
        .Play(this, Animator2D.KnownProperties.Location, new SafeInvoker((() =>
        {
            timer1.Enabled = true;
        })));
    
        base.OnLoad(e);
    }
    

    我用这种方法。 但没用

    所以我改变了方法。

    private Timer timer1 = new Timer();
    
    protected override void OnLoad(EventArgs e)
    {
        timer1.Interval = 25;
        timer1.Tick += timer1_Tick;
    
        tempX = this.Location.X;
        new Animator2D(new Path2D(-300, 23, this.Location.Y, this.Location.Y, 1500, AnimationFunctions.ExponentialEaseOut))
        .Play(this, Animator2D.KnownProperties.Location, new SafeInvoker((() =>
        {
            Invoke(new Action(() => timer1.Enabled = true));
        })));
    
        base.OnLoad(e);
    }
    

    它起作用了。

    我不知道两种方法的区别。
    通过调试器,即使使用第一个方法,timer1的启用值也将更改为True。

    我想知道为什么会这样。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Fabjan    5 年前

    说明:

    这是因为方法 Invoke 在与 control's underlying thread (在我们的例子中是UI线程)。将上下文看作线程的当前状态,以及它在特定时间如何查看内存。

    所以当我们不使用 援引 很可能代码运行在另一个线程上,该线程还包含 timer1 . 代码集 Enabled 属性到 true 在特定线程的上下文中。把它想象成你有两个定时器而不是一个 A B .

    结论:

    为了避免这种混乱,我们应该经常使用 援引 当我们在多线程环境中工作时需要更新表单中的字段或属性时。