I am trying to start a new thread and pass an argument to one of my methods. The argument is a List<string> and contains about 20 string items. I can pass the array fine using the following code:
List<string> strList = new List<string>();
Thread newThread = new Thread(new ParameterizedThreadStart(Class.Method));
newThread.Start(strList);
My Method is defined as:
public void Method(object strList)
{
//code
}
My question then is how can I run a foreach loop through each string that is contained in this object?
Three options:
Use
ParameterizedThreadStartas you are, and cast within the method:Use an anonymous function to capture the variable in a strongly typed way, and call a strongly-typed method from the anonymous function:
Use a higher-level abstraction such as the Task Parallel Library or Parallel LINQ instead; depending on what you’re doing, this may make things simpler.
If you do want to start a new thread, I’d use the second approach – keep the “dirtiness” localized to the method starting a new thread. Any of these approaches will work though. Note that if you had more than one piece of information to pass to the new thread, the second approach ends up being simpler than creating a
Tupleand unpacking it.