tags:

views:

26

answers:

1

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);
A: 

You can set the variable value inside the anonymous method:

string calStatus = string.Empty;
SynchronizedInvoke(lblCurrCalStatus, () => calStatus = lblCurrCalStatus.Text);
Fredrik Mörk
Thanks, that works!
Pieter