I have a common method in c#.
the ReadfromSource
method performs different operations based on the configuration parameters passed.
It performs operations like
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.