簡體   English   中英

在 WinFormAnimation 中使用時,啟用值為 true 的計時器不起作用

[英]Timer with Enabled value true does not work when using in WinFormAnimation

我試圖讓 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 的 Enabled 值也會更改為 True。

我想知道為什么會發生這種情況。

解釋:

發生這種情況是因為方法Invoke在與控件的底層線程(在我們的例子中是 UI 線程)相同的線程上下文中運行代碼。 將上下文視為線程的當前狀態以及它在特定時間查看內存的方式。

因此,當我們不使用Invoke時,代碼很可能在另一個包含timer1線程上運行。 該代碼在該特定線程的上下文中將Enabled屬性設置為true 把它想象成你有兩個定時器而不是一個 - 一個在線程A ,另一個在線程B

結論:

為了避免這種混亂,當我們在多線程環境中工作時需要更新表單中的字段或屬性時,我們應該始終使用Invoke

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM