I have to restart all task immediately after completion of the same. Please have a look into my program below;
class Program
{
static async Task Main(string[] args)
{
int _count = 1;
while (true)
{
await ProcessTasksAsync();
Console.Write("----Restart Tasks----" (_count ).ToString() Environment.NewLine);
await Task.Delay(2000);
}
}
static async Task ProcessTasksAsync()
{
Task<int> taskA = LongTaskA(10);
Task<int> taskB = MediumTaskB(10);
Task<int> taskC = ImmediateTaskC(10);
var tasks = new[] { taskA, taskB, taskC };
var processingTasks = tasks.Select(AwaitAndProcessAsync).ToList();
await Task.WhenAll(processingTasks);
}
static async Task AwaitAndProcessAsync(Task<int> task)
{
var result = await task;
Console.WriteLine("Return Result: " result);
}
static async Task<int> LongTaskA(int _processingCount)
{
for (int i = 0; i < _processingCount; i )
{
Console.Write(string.Format("LongTaskA:{0}", i.ToString()) Environment.NewLine);
await Task.Delay(7000);
}
return 1;
}
static async Task<int> MediumTaskB(int _processingCount)
{
for (int i = 0; i < _processingCount; i )
{
Console.Write(string.Format("MediumTaskB:{0}", i.ToString()) Environment.NewLine);
await Task.Delay(3000);
}
return 2;
}
static async Task<int> ImmediateTaskC(int _processingCount)
{
for (int i = 0; i < _processingCount; i )
{
Console.Write(string.Format("ImmediateTaskC:{0}", i.ToString()) Environment.NewLine);
await Task.Delay(1000);
}
return 3;
}
}
The Tasks A, B & C runs parallelly. But, even though the completion of certain task doesn't get restart after completion of the same. As i used "Whenall" it waits to complete the other task.
I want to restart each task after completion of the same. How can i achieve that?
Thanks, Shenu
CodePudding user response:
Your program currently runs the three tasks concurrently, (asynchronously) waits for them all to complete, and then does that in a loop.
If you want to run each task in a loop, then you just move the loop:
static async Task ProcessTasksAsync()
{
Task<int> taskA = LoopA(10);
Task<int> taskB = LoopB(10);
Task<int> taskC = LoopC(10);
await Task.WhenAll(taskA, taskB, taskC);
}
static async Task LoopA()
{
while (true)
await AwaitAndProcessAsync(LongTaskA(10));
}
static async Task LoopB()
{
while (true)
await AwaitAndProcessAsync(MediumTaskB(10));
}
static async Task LoopC()
{
while (true)
await AwaitAndProcessAsync(ImmediateTaskC(10));
}