Reputation: 67
I have big problem with Task
method, and async await.
I have 4 methods type:
private async Task Name(parameters)
{
}
And how to I can call all 4 methods to execute parallel, and to optimize time execution. Focus is constructor. I try many things. I put some here how I call in constructor:
1.
Parallel.Invoke(
() => OnLoadPrometDanKorisnikDatum(KorisnikID, PomocnaDnDDatnaDat, DatumVrednost).Wait(),
() => OnLoadPrometNedelja(KorisnikID, PomocnaDnDDatnaDatNedelja).Wait(),
() => OnLoadPrometMesec(KorisnikID, PomocnaVrednostMeseciPicker).Wait(),
() => OnLoadPrometGodina(KorisnikID, 0).Wait()
);
This is work but when you go on page 2nd or 3rd time exception throw that List
is empty which take data from API (some of method).
Name
method; and that 4 times that don't work. I don't know what to do. First method execution is about 6,7 sec. Second method is about 4 sec. Third 6 sec. Fourth 6sec.
Final need me to execute 4 method parallely and wait all that data from that 4 method. Because from that data I fill data chart later. Is empty list throw exception.
Upvotes: 1
Views: 170
Reputation: 20372
You can use Task.WhenAll
to let the methods execute in parallel:
await Task.WhenAll(
OnLoadPrometDanKorisnikDatum(KorisnikID, PomocnaDnDDatnaDat, DatumVrednost),
OnLoadPrometNedelja(KorisnikID, PomocnaDnDDatnaDatNedelja),
OnLoadPrometMesec(KorisnikID, PomocnaVrednostMeseciPicker),
OnLoadPrometGodina(KorisnikID, 0)
);
Task.WhenAll
returns a new Task
that completes when all the provided Tasks
have completed.
Upvotes: 1