I use this method courtesy of casperOne to set property values on form elements if an invoke is required.
static void SynchronizedInvoke(ISynchronizeInvoke sync, Action action)
{
// If the invoke is not required, then invoke here and get out.
if (!sync.InvokeRequired)
{
// Execute action.
action();
// Get out.
return;
}
// Marshal to the required thread.
sync.Invoke(action, new object[] { });
}
This works:
// Set a label's text
SynchronizedInvoke(lblCurrCalStatus, () => lblCurrCalStatus.Text = "Downloading...");
For obvious reasons, this wouldn't work:
// Retrieve a label's text
string calStatus = SynchronizedInvoke(lblCurrCalStatus, () => lblCurrCalStatus.Text);
Is there a function similar to SynchronizedInvoke
that can return a property value? This would require a universal return type and a cast like so:
// Retrieve a label's text
string calStatus = (string)SynchronizedInvokeReturn(lblCurrCalStatus, () => lblCurrCalStatus.Text);