C# Xamarin表单全局变量更新比代码更新慢
我有个问题。我在App.xaml.cs中使用以下代码:C# Xamarin表单全局变量更新比代码更新慢,c#,xamarin,xamarin.forms,xamarin.android,xamarin.ios,C#,Xamarin,Xamarin.forms,Xamarin.android,Xamarin.ios,我有个问题。我在App.xaml.cs中使用以下代码: public static int agentId; public static List<Agent> agents; public App() { InitializeComponent(); loadingAgents += onLoadingAgents; LoadAgentList(); MainPage = new MainPage(); } private event Eve
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);
}
}
publicstaticintagentid;
公共静态列表代理;
公共应用程序()
{
初始化组件();
装载剂+=装载剂;
LoadAgentList();
主页=新主页();
}
private EventHandler loadingAgents=委托{};
私有异步void onLoadingAgent(对象发送方、事件args args)
{
Agents=wait RestService.GetAgents();
}
私有void加载代理列表()
{
加载代理(此,EventArgs.Empty);
}
公共静态int代理
{
得到
{
退货代理;
}
设置
{
agentId=值;
}
}
公共静态列表代理
{
得到
{
如果(代理==null)
{
代理=新列表();
}
退货代理;
}
设置
{
代理人=价值;
AgentId=Agents.Min(x=>x.Id);
}
}
现在,它应该做的是:
代理列表中
列表代理
,它就会将AgentId设置为代理
列表的最小Id
在点击这一行之前,我如何等待变量完成:
MainPage=newmainpage()代码>?首先,我认为没有必要使用私有事件处理程序加载代理程序。然后,您得到的代理程序是一个异步操作,因此MainPage=newmainpage()调用方法时已执行code>(此时,代理可能为null)。通常,我们不会在构造函数中调用异步任务来获取数据,您可以在OnStart()
方法中执行
您可以尝试进行如下更改:
public App()
{
InitializeComponent();
}
protected async override void OnStart()
{
Agents = await RestService.GetAgents();
MainPage = new MainPage();
}
首先,我认为没有必要使用private event EventHandler loadingAgents
。然后您会发现Agents
是一个异步操作,因此MainPage=new MainPage()调用方法时已执行code>(此时,代理可能为null)。通常,我们不会在构造函数中调用异步任务来获取数据,您可以在OnStart()
方法中执行
您可以尝试进行如下更改:
public App()
{
InitializeComponent();
}
protected async override void OnStart()
{
Agents = await RestService.GetAgents();
MainPage = new MainPage();
}