I have this general function to invoke a WinForm control:
public static void Invoke(this Control c, Action action)
{
if (c.InvokeRequired)
c.TopLevelControl.Invoke(action);
else
action();
}
I'm thinking of making it better by bringing harsher constraints to prevent things that are meaningless, may be like:
button1.Invoke(() => list.Add(1));
Also there can be redundant typing like:
button1.Invoke(() => button1.Hide());
since we are already specifying the this
is button1
.
So I made it:
public static void Invoke<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
c.TopLevelControl.Invoke(action);
else
action(c);
}
Now I'll have to call,
button1.Invoke((c) => c.Hide());
or
button1.Invoke((c) => button1.Hide());
Now I kind of feel that even then there is some more than required typing. If I'm specifying this
is button1
, then in the lambda expression I do not want to specify a dummy variable c
again to tell where to operate on. Is there anyway I can make this shorter again? Perhaps like
button1.Invoke(Hide);
or
button1.Hide.Invoke();
or so in C#?