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

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

问题描述

什么了最优雅的方式来调用一个getter或setter异步方法在C#?

下面是一些伪code,以帮助解释一下。

 异步任务<&IEnumerable的GT; MyAsyncMethod()
{
    返回等待DoSomethingAsync();
}公共IEnumerable的MYLIST
{
    得到
    {
         //调用MyAsyncMethod()这里
    }
}


解决方案

我真的需要调用从GET方法,发起由于我的解耦架构。所以,我想出了下面的实现。

用法: 标题的是一个视图模型或对象,您可以静态地声明为一个网页资源。绑定到它该值将得到填充,而不阻塞UI时的getTitle()返回。

 字符串_title;
公共字符串标题
{
    得到
    {
        如果(_title == NULL)
        {
            Deployment.Current.Dispatcher.InvokeAsync(异步()=> {标题=等待的getTitle();});
        }
        返回_title;
    }
    组
    {
        如果(值!= _title)
        {
            _title =价值;
            RaisePropertyChanged(标题);
        }
    }
}

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
    }
}

解决方案

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

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天全站免登陆