.NET: Best way to execute a lambda on UI thread after a delay?

后端 未结 2 487
予麋鹿
予麋鹿 2021-01-01 22:04

I had a situation come up that required running a lambda expression on the UI thread after a delay. I thought of several ways to do this and finally settled on this approach

2条回答
  •  悲&欢浪女
    2021-01-01 22:51

    I think the simplest way is using System.Windows.Forms.Timer, if lambda isnt some random function.

    this._timer.Interval = 1000;
    this._timer.Tick += (s, e) => this.textBlock.Text = "Done";
    

    If labda has no need to be executed in the loop, add this;

    this.timer1.Tick += (s, e) => this.timer1.Stop();
    

    And call

    this.timer1.Start();
    

    where it needed.

    Another way is using Invoke methodes.

    delegate void FooHandler();
    
    private void button1_Click(object sender, EventArgs e)
            {
    
                FooHandler handle = () =>  Thread.Sleep(1000); 
                handle.BeginInvoke(result => { ((FooHandler)((AsyncResult)result).AsyncDelegate).EndInvoke(result); this.textBox1.Invoke((FooHandler)(() => this.textBox1.Text = "Done")); }, null);
            }
    

    Control.Invoke guarantees that delegate would be executed in the UI thread (where parent window main descriptor exists)

    Maybe exists the better variant.

提交回复
热议问题