1

我有一个类似的基类:

public abstract class PageBase
{
    public PageBase() { }

    public Task<object> Refresh(ModelRequirements requirements)
    {
        // does work of talking to server and getting data
    }

    private DataStates _dataState;
    public DataStates DataState()
    {
        get { _dataState = value; }

        set
        {
            var e = new DataStateChangingEventArgs();

            // the following method raises the changing event.
            // it does not return a task, and cannot be awaited.
            OnDataStateChanging(e);

            if (e.Cancel)
                return;

            _dataState = value;
        }
    }

    public event EventHandler<DataStateChangingEventArgs> DataStateChanging;
    protected virtual void OnDataStateChanging(DataStateChangingEventArgs e)
    {
        var dataStateChanging = DataStateChanging;
        if (DataStateChanging != null)
            DataStateChanging(this, e);
    }
}

我实现了这样的页面:

public class ContactsSearchPage : PageBase
{
    public ContactsSearchPage() { }

    private ContactModel Model {get; set;}

    protected async override void OnDataStateChanging(DataStateChangingEventArgs e)
    {
        // make new requirements
        var contactRequirements = new ContactRequirements();

        // Because the Refresh is awaited, it returns here and the rest 
        // of the DataState setter executes
        var refreshResult = await Refresh(contactRequirements);

        // set the property
        Model = refreshResult as ContactModel;

        // if the server returned null don't allow the data-state change to proceed
        if (Model == null)
            e.Cancel = true;
    }
}

等待刷新(在 OnDataStateChanging 覆盖内)是一个问题,因为它会返回。在不让 OnDataStateChanging 返回任务的情况下,这种模式有解决方案吗?

4

1 回答 1

2

期望属性设置器实际上会设置属性,并且它会在设置器返回之前执行此操作。违背这个期望会引起混乱。

这种模式有解决方案吗?

我建议将您的属性更改为 getter,以及处理该集合的方法:

public DataStates DataState { get; private set; }

public Task UpdateDataStateAsync()
{
   // ... Use await as necessary

这将使您的 API 与内部实际发生的情况相匹配,并且更容易理解。

于 2013-04-19T16:11:25.293 回答