如何从 getter 或 setter 调用异步方法? [英] How to call an async method from a getter or setter?

查看:62
本文介绍了如何从 getter 或 setter 调用异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 C# 中的 getter 或 setter 调用异步方法的最优雅的方法是什么?

What'd be the most elegant way to call an async method from a getter or setter in C#?

这里有一些伪代码来帮助解释我自己.

Here's some pseudo-code to help explain myself.

async Task<IEnumerable> MyAsyncMethod()
{
    return await DoSomethingAsync();
}

public IEnumerable MyList
{
    get
    {
         //call MyAsyncMethod() here
    }
}

推荐答案

由于我的解耦架构,我确实需要调用源自 get 方法.所以我想出了以下实现.

I really needed the call to originate from the get method, due to my decoupled architecture. So I came up with the following implementation.

用法: Title 位于 ViewModel 或您可以静态声明为页面资源的对象中.绑定到它,当 getTitle() 返回时,该值将被填充而不阻塞 UI.

Usage: Title is in a ViewModel or an object you could statically declare as a page resource. Bind to it and the value will get populated without blocking the UI, when getTitle() returns.

string _Title;
public string Title
{
    get
    {
        if (_Title == null)
        {   
            Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });
        }
        return _Title;
    }
    set
    {
        if (value != _Title)
        {
            _Title = value;
            RaisePropertyChanged("Title");
        }
    }
}

这篇关于如何从 getter 或 setter 调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆