简体   繁体   中英

C# - Looping through object parameter that was passed from new thread

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 ParameterizedThreadStart as you are, and cast within the method:

     public void Method(object strList) { List<string> list = (List<string>) strList; // Use list here } 
  • Use an anonymous function to capture the variable in a strongly typed way, and call a strongly-typed method from the anonymous function:

     List<string> strList = new List<string>(); ThreadStart action = () => Method(strList); new Thread(action).Start(); ... public void Method(List<string> list) { // Use list here } 
  • 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 Tuple and unpacking it.

You have to typecast the object to your list type like eg the following:

public void Method(object strList)
{
    var list = (List<string>)strList;
    foreach ( var s in list )
    {
        // Do something.
    }
}

您必须将对象强制转换为实际类型,然后您才能使用foreach。

Cast your object with (List<string> ) and then use the iteration through it

for (int i = 0; i < list.Count; i++) // Loop through List with for
        {
            Console.WriteLine(list[i]);
        }

You'll have to cast it back to a list of strings like so:

public void Method(object strList)
{
    List<string> internalStringList = strList as List<string>;
    //this is a save cast the "internalStringList" variable will 
    //be null if the cast fails.
}

You can also do this:

List<string> internalStringList = (List<string>) strList;

but this could throw an InvalidCastException if strList isn't a List

To be safe:

public void Method(object strList)
{
   var list = strList as List<string>;
   if (list != null)
    { 
       foreach(var item in list )
       {
          //code here
       }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM