I am an enthusiast developer rather than a professional one, and as such I don't have a highly technical understanding of why some issues are as they are. Recently, I've been working on applications where I've been trying to improve responsiveness through use of backgroundworkers to handle various database calls.
Once the backgroundworkers complete, I need to update the UI, and so I normally do something like the following:
private delegate void safeSetTextDelegate(Control control, string text);
public static void SafeSetText(this Control control, string text)
{
if(control.InvokeRequired)
{
safeSetTextDelegate _delegate = new safeSetTextDelegate(SafeSetText);
control.Invoke(_delegate, new object[] { control, text});
}
else
{
control.Text = text;
}
}
Now, obviously this works. But as the number of extension methods I find that I need starts to grow (I have them for setting styles, adding child controls dynamically, adding rows to datagridviews etc), I was wondering why there isn't a set of standard methods available in the .Net WinForms language / model for these types of things, or even why the InvokeRequired checks aren't made automatically behind-the-scenes and a delegate applied as required (my guess is that this is a performance issue - why check the calling thread when in the majority of cases it simply isn't required). I have tried to research this, and haven't found any decent answers.
If I was to summarize this into a set of questions:
- Is there anything inherently bad / wrong in my approach (backgroundworkers updating controls via extension methods that check
InvokeRequired
) - Is my thinking as to why the various methods in the .Net WinForms don't automatically do
InvokeRequired
checks correct (how much overhead is there in calling InvokeRequired)? - Similarly, is there are reason why thread-safe methods for common UI updates don't exist in the .Net WinForms specification?