sooprise
sooprise

Reputation: 23187

Invoke With Two Parameters Of Different Variable Types?

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
        }
    }

Upvotes: 1

Views: 3752

Answers (3)

desco
desco

Reputation: 16782

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); });

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500855

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.

Upvotes: 5

Jimmy Hoffa
Jimmy Hoffa

Reputation: 5967

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

Upvotes: 0

Related Questions