【问题标题】:How to make an 'await' for multiple variables on return async function如何在返回异步函数时为多个变量“等待”
【发布时间】:2016-10-02 18:14:53
【问题描述】:

我有一个async 函数:

public async Task<List<Data>> GetDataAsync()
{
    //get data
    return new List<Data>; //but then filled with real data
}

我这样称呼它:

listView.ItemsSource = await sc.GetSensorsAsync();

这样当函数完成获取数据时会弹出listView。

现在我想将相同的 List&lt;Data&gt; 保存到变量中,但不再调用 sc.GetSensorDataAsync()

我试过了:

List<Data> data = await sc.GetSensorsAsync();
listView.ItemsSource = data;

但是因为函数是异步的,所以当data变量还是null时,它会执行listView.ItemsSource = data;

如何解决这个问题,让listView.ItemsSourcedata 都包含返回值?

【问题讨论】:

  • But because the function is async, it will execute the listView.ItemsSource = data; when the data variable is still null 在分配数据之前放置 await 怎么可能?也许方法返回 null?

标签: c# asynchronous xamarin async-await task-parallel-library


【解决方案1】:

但是因为函数是异步的,所以会执行 listView.ItemsSource = 数据;当数据变量仍然为空时。

不,这不是 async-await 的工作方式。异步方法完成后,异步方法只会执行延续(await 之后的行)。这意味着,保证GetSensorsAsync 将在您将列表分配给ListView.ItemSource 的下一行之前完成。

如果您收到 null 值,那只是因为您的方法返回 null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 2020-08-19
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多