How to pass multiple parameter in Task

28,070

Solution 1

You could use lambda expression, or a Func to pass parameters:)

public Form1()
{
    InitializeComponent();

    Task task = new Task(() => this.GetPivotedDataTable("x",DateTime.UtcNow,1,"test"));
    task.Start();
}

public void GetPivotedDataTable(string data, DateTime date, int id, string flag)
{
    // Do stuff
}

Solution 2

In case that your parameters are of diferent types you could use an array of object and then typecast back to the original types.

Check out this console application example:

    static void Main(string[] args)
    {
        var param1String = "Life universe and everything";
        var param2Int = 42;

        var task = new Task((stateObj) =>
            {
                var paramsArr = (object[])stateObj; // typecast back to array of object

                var myParam1String = (string)paramsArr[0]; // typecast back to string 
                var myParam2Int = (int)paramsArr[1]; // typecast back to int 

                Console.WriteLine("");
                Console.WriteLine(string.Format("{0}={1}", myParam1String, myParam2Int));
            },
            new object[] { param1String, param2Int } // package all params in an array of object
        );

        Console.WriteLine("Before Starting Task");
        task.Start();
        Console.WriteLine("After Starting Task");

        Console.ReadKey(); 
    }
Share:
28,070
J R B
Author by

J R B

.Net Developer

Updated on July 09, 2022

Comments

  • J R B
    J R B almost 2 years

    I have a function GetPivotedDataTable(data, "date", "id", "flag") is returning data in Pivoted format. I want to call this method using Task but how to pass multiple parameter in Task.