0
I have a class:
public class Robo {
public async Task Ligar() {
/*
* Algo que pode demorar ou nao depende do status do robo
* */
}
}
public class TesteRobo {
public void Main() {
List < Robo > robos = new List < Robo > ();
foreach(var item in robos) {
item.Ligar();
/**
* não posso ligar todos no mesmo instante, para não pesar no processamento
* preciso que após o primeiro ser executado seja esperado um tempo, por exemplo 30 segundos
* para poder chamar o próximo
* /
}
}
}
I would like to know an alternative not to use Thread.Sleep()
?
It is possible to replace the "for"
for Task.Run
with lambda
and linq
?
Grateful
Well, just informing I solved that way:
class Robot
{
private readonly string name;
public string Name { get { return this.name; } }
public Robot(string name)
{
this.name = name;
}
public void Ligar()
{
Console.WriteLine($"Robo: {name} ligando");
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"Robo: {name} iniciando");
Thread.Sleep(500);
}
Console.WriteLine($"Robo: {name} ligando");
}
}
private static void DoWorkRobots()
{
List<Robot> robots = new List<Robot>();
for (int i = 0; i < 3; i++)
{
Robot robot = new Robot("Robo " + i);
robots.Add(robot);
}
foreach (var item in robots)
{
var t = Task.Run(() =>
{
Console.WriteLine($"{item.Name} - Antes de ligar - {DateTime.Now}");
item.Ligar();
Console.WriteLine($"{item.Name} - Depois de ligar - {DateTime.Now}");
Thread.Sleep(4000);
});
t.Wait(2000);
}
Console.WriteLine("Aguarda 5 segundos");
Thread.Sleep(5000);
Console.WriteLine("Terminado");
}
static void Main(){
Task vs = Task.Run(() => DoWorkRobots());
vs.Wait();
}
That’s about what I need, maybe I need a few tweaks and maybe help someone around here too
It may be interesting if you try to run them all at once using a parallel loop (Parallel.Foreach()). In case you didn’t want to weigh in the processing, you can try to run it with low priority. This way you use all the colors of your processor and your task will not burden the both system.
– Bruno Soares
Well, the point is, I can’t run them all at once because it’s a SOAP request and a lot of them can overload Webservice. That’s why I need a delay
– Peres
I get the point. A suggestion: maybe it is interesting to treat this problem in the webservice itself, so that it supports more requests.
– Bruno Soares
The webservice is from another company, and was created long ago (about 10 years probably) and has no way to change.
– Peres