I'm working with async-await methods and I can't get next functionality:
I have a sync wrapper method (MethodSync
) that calls an async method (MethodA_Async
) and then does some stuff (MethodB
).
After that, it enters to a loop where for each item it does some stuff (MethodC
) and then an async method (MethodE_Async
) is run but waiting for MethodA_Async
to finish (that is why I pass the task that MethodA_Async
returns: to await for it to finish).
Finally, it performs other stuff (MethodD
) and waits for all MethodE_Async
to finish.
The problem is that it is not working and it enters to an infinite loop of waiting.
private async Task<bool> MethodA_Async()
{
bool finish = false;
await Task.Run(()=>
{
// Doing another things
finish = true;
});
return finish;
}
private void MethodB() { }
private void MethodC() { }
private void MethodD() { }
private async Task MethodE_Async (Task<bool> methodATask, int item)
{
await Task.Run(async() =>
{
// Waits for MethodA_Async to finish
bool finish = await methodATask;
// Other logic that works on item parameter.
var result = 2*item;
});
}
public bool MethodSync()
{
// Starts MethodA_Async
var taskMethodA = MethodA_Async();
// Doing other things that do not depend upon MethodA_Async
MethodB();
// Iterations
var tasksDependingOnMethodA = new List<Task>();
var items = new List<int>{ 1, 2, 3 };
foreach(var item in items)
{
// Doing other things that do not depend upon MethodA_Async
MethodC();
// MethodE_Async starts
tasksDependingOnMethodA.Add(MethodE_Async(taskMethodA, item));
}
// Other method that does not depend upon MethodA_Async
MethodD();
// Wait for all MethodE_Async methods to finish
Task.WhenAll(tasksDependingOnMethodA).GetAwaiter().GetResult();
return true;
}
I'd appreciate any guidance you could give me.