我是 C# 中异步编程的新手。我使用异步的动机是避免在 win 表单应用程序中锁定 UI 线程,而无需使用一堆后台工作人员或显式线程等。无论如何,这是我目前的理解。
为了等待一个可等待的函数,调用函数需要是异步的。好吧,我发现自己经常使用以下模式......
public class SomeViewModel
{
private Thing m_thing;
public SomeViewModel()
{
ReloadThing();
}
public Thing Thing
{
get {
return m_thing;
}
protected set {
m_thing = value;
NotifyPropertyChanged();
}
}
public async void ReloadThing()
{
Thing = await FetchThing();
}
private async Task<Thing> FetchThing()
{
// entity framework code
return await DbSet<Things>.SingleAsync();
}
}
对于我的 View (表单),它基本上是对 MVVM 样式 View 模型的一些尝试。
但是,模式只是异步包装函数,所以我可以使用等待。我应该在这里使用更好的方法吗?
最佳答案
I guess the over-all question is whether there's a more direct way to load data in a non-blocking way within a view model like this, so that a view (win form) can bind to a property backed by that async data? That's about the most specific-to-my-situation question.
您可以在 async data binding 上找到我的文章有用。在其中,我介绍了
Task<T>
的数据可绑定(bind)包装器。 ,它删除了很多关于异步代码更新数据绑定(bind)的样板代码(以及正确处理错误情况等)。该代码的更新版本是 on GitHub .
关于c# - 我发现自己编写包装函数纯粹是为了等待异步函数。如何避免这种模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36296682/