How to get information about an exception raised by the target of Control.Invoke
<p>I have a 'generic' boiler plate static method for checking for InvokeRequired and invoking an associated action accordingly.</p>

<p>If an unhandled exception is raised by the action, the stack trace isn't much help because it starts from here. I can get information about the control, but that isn't always much help. I was wondering if it is possible to get 'something' useful out of the Action - other that 'Target'. (Note that the Action is often a lambda or anonymous delegate...)</p>

<pre><code>    public static void Invoke(Control ctrl, Action action)
    {
        if (ctrl == null)
            throw new ArgumentNullException("ctrl");
        if (action == null)
            return;

        var invokeRequired = ctrl.InvokeRequired;
        try
        {
            if (ctrl.InvokeRequired)
                ctrl.Invoke(action);
            else
                action();
        }
        catch (Exception ex)
        {
            throw new Exception(String.Format("Invoke error, ctrl={0}, action Target={1}", ctrl.Name, action.Target), ex);
        }
    }
</code></pre>

<p>EDIT: In line with <a href="#258417" rel="nofollow">this answer</a>, here is the new overload (also slightly improved)</p>

<pre><code>public static void Invoke(Control ctrl, Action action, string context)
{
    if (ctrl == null)
        throw new ArgumentNullException("ctrl");
    if (action == null)
        return; //not sure it's worththrowing an exception here...

    var invokeRequired = ctrl.InvokeRequired;
    try
    {
        if (invokeRequired)
            ctrl.Invoke(action);
        else
            action();
    }
    catch (Exception ex)
    {
        var ps = invokeRequired ? "" : " - has the target control been initialised?";
        var errmsg = String.Format("Invoke error, ctrl={0}, action Target={1}, context={2}{3}", ctrl.Name, action.Target, context, ps);
        throw new Exception(errmsg, ex);
    }
}
</code></pre>
