我不确定这个状态。我需要从数据库异步获取数据。
我有 DB 类
public class Db{
public async Task<ObservableCollection<Person>> GetAllPerson()
{
using (var context = new Db())
{
// get data and return ObservableCollection<Person>
}
}
Run Code Online (Sandbox Code Playgroud)
}
在 ViewModel 中我调用 LoadData 函数。
public class VM{
public ObservableCollection<Person> Person { get; set; }
private readonly DB sqlRepository;
public VM()
{
sqlRepository=new DB();
LoadData();
}
private async void LoadData()
{
Person= await sqlRepository.GetAllPerson();
}
Run Code Online (Sandbox Code Playgroud)
}
我收到警告:警告 CS1998 此异步方法缺少“等待”运算符,并将同步运行。
如何异步运行我的函数?我应该使用吗?
Person=await Task.Run(()=>this.sqlRepository.GetAllPerson());
Run Code Online (Sandbox Code Playgroud)
如何异步运行我的函数?
您正在从错误的方向处理问题。您正在尝试“从外到内” - 您的 ViewModel 想要异步加载数据库数据。这是描述问题的好方法,但却是解决问题的错误方法。
为了更容易地解决这个问题,请从另一端开始。无论实际调用数据库的方法(例如,实体框架调用)都应该首先异步,然后async从那里开始增长。最终你会得到类似的结果:
public async Task<ObservableCollection<Person>> GetAllPersonAsync()
{
using (var context = new Db())
{
// This code wasn't shown in the question.
// But from the compiler warning, it was probably using something like
// var people = People.ToList();
// return new ObservableCollection<Person>(people);
// And the async version should be:
var people = await People.ToListAsync();
return new ObservableCollection<Person>(people);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将其消费为:
private async void LoadData()
{
Person = await sqlRepository.GetAllPersonAsync();
}
Run Code Online (Sandbox Code Playgroud)
但我建议按照我的MVVM 异步数据绑定文章NotifyTask中所述使用它。这种方法将使您能够对繁忙的旋转器等进行数据绑定。
我应该使用[
Task.Run]吗?
不,这是“假异步”——您的代码表现得像异步的,但实际上只是在后台线程上同步运行。
| 归档时间: |
|
| 查看次数: |
7558 次 |
| 最近记录: |