Avoiding InvokeRequired

时间:2023-03-09 03:21:39
Avoiding InvokeRequired

Just read a good article to do cross-thread calling in an easy and elegant way.

It is amazing for its simplicity and elegancy:

 static class ControlExtensions
{
public static void InvokeOnOwnerThread<T>(this T control, Action<T> invoker) where T : Control
{
if (control.InvokeRequired)
control.Invoke(invoker, control);
else
invoker(control);
}
}

Only 10 lines to make the further calling a single line and extremely easy to read, very beautiful the way I like.

private void UpdateTextBoxFromSomeThread(string message)
{
textBox1.InvokeOnOwnerThread((txtBox) => txtBox.Text = message);
}

Would like to give all the credits to its author.

Original link: http://www.codeproject.com/Tips/374741/Avoiding-InvokeRequired