Whenever I want to modify a winform from another thread, I need to use
->Invoke(delegate, params)
so that the modification occurs in the winf
If you're using C# 3, you can use lambda, and in C# 2, use anonymous delegates. These simplify the syntax when there's no need to reuse the behavior. One thing I always do is to do the synchronization in the form code, not in the controller. The controller shouldn't be bothered with these sort of "plumbing" problems that are more specific to the technology than to the controller logic.
public void ResetFields()
{
// use "delegate" instead of "() =>" if .Net version < 3.5
InvokeOnFormThread(() =>
{
firstInput.Text = Defaults.FirstInput;
secondInput.Text = Defaults.SecondInput;
thirdChoice.SelectedIndex = Defaults.ThirdChoice;
});
}
// change Action to MethodInvoker for .Net versions less than 3.5
private void InvokeOnFormThread(Action behavior)
{
if (IsHandleCreated && InvokeRequired)
{
Invoke(behavior);
}
else
{
behavior();
}
}
As a practice, make all public methods in your form call "InvokeOnFormThread." Alternately, you could use AOP to intercept public method calls on your form and call "InvokeOnFormThread," but the above has worked well enough (if you're consistent and remember to always do it on public methods on the form or UserControls).