【问题标题】:How to await for without return task method如何等待没有返回任务的方法
【发布时间】:2018-07-31 21:13:45
【问题描述】:

我正在了解asyncawait。我有一个用于对话消息的异步方法,我正在等待另一种方法。

我的代码=>

private async Task CalculateProcess()
{
    dialogCoordinator = DialogCoordinator.Instance;
    // Show...
    ProgressDialogController controller = await dialogCoordinator.ShowProgressAsync(this, "HEADER", "MESSAGE");
    controller.SetIndeterminate();

    // Do your work... 
    await testing();//I want to await testing method but i cant await testing because testing method no return task
    // Close...
    await controller.CloseAsync();
}
private void testing()
{
   for(int i=0;i<=1000000;i++)
    {

    }//Looping is example                
}

我想等待测试方法,但是如果我想使用等待,我需要从测试中返回任务。如果我没有任何其他返回任务,我如何等待测试方法?

【问题讨论】:

标签: c# async-await


【解决方案1】:

如果您真的想等待该方法,那么可以这样做:

private async Task CalculateProcess()
{
    dialogCoordinator = DialogCoordinator.Instance;
    // Show...
    ProgressDialogController controller = await dialogCoordinator.ShowProgressAsync(this, "HEADER", "MESSAGE");
    controller.SetIndeterminate();

    // Do your work... 
    await testing();
    // Close...
    await controller.CloseAsync();
}

private Task testing()
{
   for(int i=0;i<=1000000;i++)
    {

    }//Looping is example                

    return Task.FromResult(0);
}

【讨论】:

  • 如果 GetRecord 方法(从数据库中获取)是异步的,那么您在测试中不需要 Task.FromResult,只需等待 GetRecord,如果它不是异步的,则调用 GetRecord 并将 Task.FromResult 留在测试方法结束。
猜你喜欢
  • 2018-04-21
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2014-10-01
  • 1970-01-01
相关资源
最近更新 更多