我有问题。我在App.xaml.cs中使用以下代码:
public static int agentId;
public static List<Agent> agents;
public App()
{
InitializeComponent();
loadingAgents += onLoadingAgents;
LoadAgentList();
MainPage = new MainPage();
}
private event EventHandler loadingAgents = delegate { };
private async void onLoadingAgents(object sender, EventArgs args)
{
Agents = await RestService.GetAgents();
}
private void LoadAgentList()
{
loadingAgents(this, EventArgs.Empty);
}
public static int AgentId
{
get
{
return agentId;
}
set
{
agentId = value;
}
}
public static List<Agent> Agents
{
get
{
if (agents == null)
{
agents = new List<Agent>();
}
return agents;
}
set
{
agents = value;
AgentId = Agents.Min(x => x.Id);
}
}
现在这应该做的是以下操作:
List<Agent> Agents
List<Agent> Agents
,它将把AgentId设置为Id
列表中的最小值Agents
问题是,在MainPage的ViewModel中,我使用了应该设置的变量,但是ViewModel的代码比需要更新变量的代码要快。
我如何在到达此行之前等待变量完成:MainPage = new MainPage();
?
[首先,我认为没有必要使用private event EventHandler loadingAgents
。然后您获得Agents
是异步操作,因此在调用该方法时已执行MainPage = new MainPage();
(此时,Agents可能为null )。通常,我们不会在构造函数中调用异步任务来获取数据,您可以在OnStart()
方法中进行操作。
您可以尝试如下更改:
public App()
{
InitializeComponent();
}
protected async override void OnStart()
{
Agents = await RestService.GetAgents();
MainPage = new MainPage();
}