views:

272

answers:

1

How would i pass some parameters to a new thread that runs a function from another class ? What i'm trying to do is to pass an array or multiple variables to a function that sits in another class and its called by a new thread.

i have tried to do it like this >

    Functions functions = new Functions();

    string[] data;

    Thread th = new Thread(new ParameterizedThreadStart(functions.Post()));

    th.Start(data);

but it shows error "No overload for method 'Post' takes 0 arguments"

Any ideas ?

+6  A: 

Since you have this flagged C# 4, the new approach to this would be:

Functions functions = new Functions();

string[] data = GetData();

Task.Factory.StartNew( () => functions.Post(data) );

If you really want to leave this using a dedicated thread, and not the Task Parallel library, you can. Given your comments, it sounds like Post() is probably defined as Post(string[] data). This will not work since ParameterizedThreadStart expects the method to be Post(object data).

You can work around this via lambdas and using ThreadStart instead of ParameterizedThreadStart, however, without changing your methods:

Functions functions = new Functions();
string[] data = GetData();
Thread th = new Thread( () =>
    {
        functions.Post(data);
    });
th.Start();
Reed Copsey