简体   繁体   中英

MultiThreading in foreach loop C#

I have a common method in c#.

the ReadfromSource method performs different operations based on the configuration parameters passed.

It performs operations like

  1. listening to a TCP port endlessly and receives the incoming data.
  2. listening to a http port endlessly and receives the incoming data.
  3. listening to a folder path endlessly and receives the incoming files.
public void ReadData(List<Configuration> configurations)
{
   foreach(var config in configurations)
   {
    ReadfromSource(Configuration config);
   }
}
public void ReadfromSource(Configuration config)
{
       while(true)
       {

        // code for reading data from tcp port

        thread.sleep(1000);      //listens for each and every second

        }
}

using multithreading, I need to run all the operations concurrently

how to implement the above scenario using mutithreading in c#, Thanks in Advance.

You can use Task.WhenAll() to run multiple tasks parallelly.

public async Task ReadData(List<Configuration> configurations)
{
    var tasks = new List<Task>();

    foreach (var config in configurations)
    {
        tasks.Add(ReadfromSource(config));
    }

    await Task.WhenAll(tasks);
}

public async Task ReadfromSource(Configuration config)
{
    while (true)
    {
        // code for reading data from tcp port
        await Task.Delay(1000);
    }
}

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