I did some UI work in C# lately and discovered all kind of cool new stuff. So cool, I couldn't resist sharing it with the world.
Lets say we have a multi-threaded application that throws tasks (TPL) in the back-end.
The tasks report back and we want to reflect it in the UI but we should update UI always in the main thread. We use Invokefor and in many places in the code we have chunks of the kind:
void SomeFunction()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(SomeFunction)
else
{
// Here goes some UI functionality
}
}
With .NET 3.0 we have Action so we can write one function like this
or even a code block like this:
Fun ...
void DoUiStuff(Action a)
{
if
(this.InvokeRequired)
this.Invoke(new MethodInvoker(a));
else
a();
}
Then whenever we want a UI action we write a lambda expression for example:
DoUiStuff(() => progressBar.Visible = true);
DoUiStuff(() => progressBar.Visible = true);
DoUiStuff(() =>
{
progressBar.Visible = false;
MessageBox.Show("Done!");
});