我有一个类似的基类:
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 返回任务的情况下,这种模式有解决方案吗?