如何在 return 异步函数上为多个变量创建 'await'
How to make an 'await' for multiple variables on return async function
我有一个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<Data>
保存到一个变量中,但不再调用 sc.GetSensorDataAsync()
。
我试过这个:
List<Data> data = await sc.GetSensorsAsync();
listView.ItemsSource = data;
但是因为函数是异步的,当data
变量仍然是null
时,它会执行listView.ItemsSource = data;
。
如何解决这个问题,使 listView.ItemsSource
和 data
都包含返回值?
But because the function is async, it will execute the
listView.ItemsSource = data; when the data variable is still null.
不,async-await 不是这样工作的。一旦异步方法完成,异步方法只会执行延续(await
之后的行)。这意味着,保证 GetSensorsAsync
将在下一行将列表分配给 ListView.ItemSource
.
之前完成
如果您收到 null
值,那只是因为您的方法返回 null
。
我有一个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<Data>
保存到一个变量中,但不再调用 sc.GetSensorDataAsync()
。
我试过这个:
List<Data> data = await sc.GetSensorsAsync();
listView.ItemsSource = data;
但是因为函数是异步的,当data
变量仍然是null
时,它会执行listView.ItemsSource = data;
。
如何解决这个问题,使 listView.ItemsSource
和 data
都包含返回值?
But because the function is async, it will execute the listView.ItemsSource = data; when the data variable is still null.
不,async-await 不是这样工作的。一旦异步方法完成,异步方法只会执行延续(await
之后的行)。这意味着,保证 GetSensorsAsync
将在下一行将列表分配给 ListView.ItemSource
.
如果您收到 null
值,那只是因为您的方法返回 null
。