-1

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.

  • 2
    explorer async await – Vivek Nuna Mar 03 '21 at 06:33
  • `how to implement the above scenario using mutithreading in c#,` `Task.Run` may be a starting point. – mjwills Mar 03 '21 at 06:34
  • I tried `Task.Run`inside the foreach loop, but the first task is alone is created and started .....remaining task is not created – Sivakumar Selvaraj Mar 03 '21 at 06:47
  • 2
    This is a complex question, "how to implement multithreading?" has no direct answer, this depends on many things, including what your ReadFromSource actually does. For I/O-bound operations, you shouldn't use Task.Run, use async I/O API instead, like `Stream.ReadAsync` – joe Mar 03 '21 at 06:55
  • You can view the same question: https://stackoverflow.com/questions/9418554/starting-a-new-thread-in-a-foreach-loop – Tahir Alvi Mar 03 '21 at 07:21
  • `I tried Task.Runinside the foreach loop, but the first task is alone is created and started .....remaining task is not created` I can't comment on code I can't see. – mjwills Mar 03 '21 at 09:16

1 Answers1

0

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);
    }
}
VahidShir
  • 2,066
  • 2
  • 17
  • 27
  • I want to remark that the code for doing TCP I/O should use the async methods of TcpClient (or whatever TCP class is being used), e.g. ReadAsync instead of Read and so on. Because OP has written above that he tried Task.Run, I want to stress that it’s usually a bad idea to wrap I/O bound stuff in a CPU-bound task (which Task.Run is), and that proper I/O bound tasks (ReadAsync, WriteAsync) should be preferred. – ckuri Mar 03 '21 at 08:19