简体   繁体   English

异步等待线程异常

[英]Async await thread exception

I have big problem with Task method, and async await.我对Task方法和异步等待有大问题。 I have 4 methods type:我有 4 种方法类型:

 private async Task Name(parameters)
 {
 }

And how to I can call all 4 methods to execute parallel, and to optimize time execution.以及如何调用所有 4 种方法来并行执行并优化时间执行。 Focus is constructor.焦点是构造函数。 I try many things.我尝试了很多东西。 I put some here how I call in constructor:我在这里放了一些我在构造函数中调用的方式:

1. 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).这是可行的,但是当您进入第 2 或第 3 次异常抛出该List为空时,它从 API(某些方法)获取数据。

  1. When try await Name method;当尝试 await Name方法时; and that 4 times that don't work.那4次不起作用。
  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.第一个方法执行大约需要 6.7 秒。 Second method is about 4 sec.第二种方法是大约 4 秒。 Third 6 sec.第三个 6 秒。 Fourth 6sec.第四个6秒。

Final need me to execute 4 method parallely and wait all that data from that 4 method.最后需要我并行执行 4 个方法并等待来自该 4 个方法的所有数据。 Because from that data I fill data chart later.因为根据这些数据,我稍后会填写数据图表。 Is empty list throw exception.是空列表抛出异常。

You can use Task.WhenAll to let the methods execute in parallel:您可以使用Task.WhenAll让方法并行执行:

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. Task.WhenAll返回一个新Task ,该Tasks在所有提供的Tasks完成后完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM