在继续之前等待完成任务的功能

问题描述 投票:-2回答:1

在继续之前,您如何等待具有任务内部的任务?

public void A()
{
    Debug.Log("before")
    CopyInfoFromDB();
    Debug.Log("after") 
}

public void CopyInfoFromDB()
{
    FirebaseDatabase.DefaultInstance.GetReference(path)
             .GetValueAsync().ContinueWith(task =>
             {
                 if (task.IsFaulted)
                 {
                     Debug.Log("failed");

                 }
            name = ...// loading local varibles from Task.result
            });
}

我希望它等待CopyInfoFromDB完成后再打印“之后”。我该如何以不同的方式编写函数A?

c# async-await task
1个回答
-1
投票

如果要使用async-await,请准备好使管道中涉及的所有方法都是异步的

public async Task A()
{
    Debug.Log("before")
    await CopyInfoFromDB();
    Debug.Log("after") 
}

public Task CopyInfoFromDB()
{
      return FirebaseDatabase.DefaultInstance
                             .GetReference(path)
                             .GetValueAsync();
}

如果GetValueAsync失败,将在您正在等待它的行上抛出异常。

© www.soinside.com 2019 - 2024. All rights reserved.