【问题标题】:How to use await in this scenario在这种情况下如何使用 await
【发布时间】:2022-01-23 11:03:51
【问题描述】:

我有一个方法如下所示

 static public async Task GetStudentDetails(studentinfo stu)
 {
   // here i am using webservice call
   // do some other operations
 }

这个方法是从另一个方法调用的,如下所示:

static public void GetUIWindow((int a, int b)
{
  someanothercall();
  studentinfo s = new Studentinfo();
  GetStudentDetails(s); // here how can i use await keyword ??
}

这里如何使用 await 关键字??

【问题讨论】:

  • await 只能用于标记为async 并返回任务的方法。在您的情况下,如果您想等待您的方法同步等待而不阻塞 UI 线程,您可以执行 GetStudentDetails(s).RunSynchronously();
  • @KunalMukherjee 你试过你的建议了吗? AFAIK 调用 promise-stype 任务的 RunSynchronously 方法总是会导致运行时异常。

标签: c# async-await


【解决方案1】:

如何使用 await 关键字??

awaitGetStudentDetails返回的任务:

await GetStudentDetails(s);

然后编译器会向您抱怨说您应该将GetUIWindow 更改为async 并返回Task。所以继续做吧:

static public async Task GetUIWindowAsync(int a, int b)

然后对所有调用GetUIWindow 的地方执行相同的操作。冲洗并重复;是async all the way

【讨论】:

    猜你喜欢
    • 2019-12-04
    • 1970-01-01
    • 2022-01-23
    • 2015-11-30
    • 2017-05-16
    • 2012-10-06
    • 2011-05-18
    • 2019-11-29
    • 2018-05-20
    相关资源
    最近更新 更多