1
votes

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).

  1. When try await Name method; and that 4 times that don't work.
  2. I try to method be void don't task that don't work too.

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.

1
This is very difficult to read; help the people who are trying to help you by formatting code as code, more clearly saying what your question is, and so on. - Eric Lippert
Thanks for clarifying; I've voted to re-open. - Eric Lippert

1 Answers

1
votes

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.