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
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.