使用await和一个实现了CancelEventArgs的事件
本文关键字:实现 CancelEventArgs 事件 一个 await 使用 | 更新日期: 2023-09-27 18:10:14
我有一个类似的基类:
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覆盖中)是一个问题,因为它返回。没有使ondatastatechange返回任务,有解决方案,这种模式?
期望属性setter将实际设置属性,并且它将在setter返回之前完成此操作。违反此期望将导致混乱。
这个模式有解决方案吗?
我建议把你的属性改成一个getter,和一个处理集合的方法:
public DataStates DataState { get; private set; }
public Task UpdateDataStateAsync()
{
// ... Use await as necessary
这将使您的API与内部实际发生的匹配,并且更容易理解。