views:

53

answers:

3

How can I write an invoke method with two parameters of differing variable types?

    public void InsertStockPrice(double Value, string Company)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<double>(InsertStockPrice), Value); // <- Not sure what to do here
        }
        else
        {
            //Do stuff
        }
    }
A: 

I think what you mean to be looking for is:

Action<Type1,Type2> yourAction = (type1Var, type2Var) => 
    {
       do stuff with type1Var and type2Var;
    }

yourAction(var1, var2);
Jimmy Hoffa
+3  A: 

I suspect this is what Jimmy meant (as Control.Invoke wouldn't really know what to do with an Action<double, string>:

public void InsertStockPrice(double value, string company)
{
    if (InvokeRequired)
    {
        MethodInvoker invoker = () => InsertStockPrice(value, company);
        Invoke(invoker);
    }
    else
    {
        // Do stuff
    }
}

If you're using C# 2:

public void InsertStockPrice(double value, string company)
{
    if (InvokeRequired)
    {
        MethodInvoker invoker = delegate { InsertStockPrice(value, company); }
        Invoke(invoker);
    }
    else
    {
        // Do stuff
    }
}

Note that I've changed the case of your parameters to fit in with normal .NET conventions.

Jon Skeet
A: 

If this pattern is often repeated in code, you can make little helper method like this one

static class UiExtensions
{
    public static void SafeInvoke(this Control control, MethodInvoker method)
    {
        if (control.InvokeRequired)
            control.Invoke(method);
        else
            method();
    }
}

this.SafeInvoke(() => { InsertStockPrices(value, company); });
desco