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.P开发者_StackOverflow中文版ost()));
th.Start(data);
but it shows error "No overload for method 'Post' takes 0 arguments"
Any ideas ?
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();
The direct answer is :
new Thread(new ParameterizedThreadStart(functions.Post/*(remove)*/));
and Functions.Post should be of the form:
void Post(object state) { string[] data = (string[]) state; .... }
If you already have a fixed void Post(string[] data)
you could add a wrapper to the Functions class:
void Post2(object state) { Post((string[]) state); }
But when using Fx4 you should really take a look at the Task library.
精彩评论