that's 4 ugly lines of code you have to write. And you need to create such a delegate for each special method signature you might want to make thread safe (the alternative is to have a standard on thread safe methods and use the same delegate type each time, but that also is pretty ugly and hard to maintain.
private void EnableButtons(bool enabled)
{
if(Safe.Invoke(this,enabled)
return;
cmdDoSomething.Enabled = enabled;
cmdStop.Enabled = !enabled;
}
Done.
Here are some other use cases for this:
public void ThreadSafeEmptyMethod()
{
if(Safe.Invoke(this))
return;
//do whatever GUI things you want here!
}
public void ThreadSafeMethodWithParams(int i, string str)
{
if(Safe.Invoke(this,i,str))
return;
//do whatever GUI things you want here!
}
public int ThreadSafeMethodWithParamsAndReturnValue(int i, string str)
{
if(InvokeRequired)
return Safe.InvokeAndReturn(this,i,str);
//do whatever GUI things you want here!
TextBox1.Text = "whatever";
return 1;
}
Under the covers there is a little reflection going on a little ugly trick in the Safe class, but the main thing to know is that when you're dealing with a different thread, performance is not really the issue here anyway, plus, it works great and you don't really notice anything in the UI (I should know - the new Regulator 2005 is using this stuff all over).
The class itself is pretty small (the solution is quite simple), but I have a whole other story about making this work *the hard way* which I'll tell when I get more time 9you *did notice I have much less time than I used to, right?;) )