在 Xamarin 中异步加载布局
Load the layout async in Xamarin
我正在尝试将内容加载到堆栈布局异步但是到目前为止没有运气。
当我浏览页面时,我将元素添加到堆栈布局。即使我在 aysnc 函数上执行它,我也会冻结,直到加载所有内容。我想显示一个 activity 指标。当指示器旋转时,我想加载布局。
我尝试在 OnAppering 方法上执行此操作,但没有成功。
protected async override OnApperaing()
{
base.OnApperaing();
for(int i = 0; i < 100; i++)
{
stacklayout.Children.Add(new Label { Text = "Some Text" });
}
}
我该如何解决这个问题?此致
您在这里没有等待任何方法,因此您的方法同步运行。
你应该会收到警告,字里行间写着什么
The async method lacks await operators...
根据你的情况,你需要做这样的事情
protected async override void OnApperaing()
{
base.OnApperaing();
for(int i = 0; i < 100; i++)
{
await Task.Run(() => {
var tcs = new TaskCompletionSource<bool>();
InvokeOnMainThread(() => {
stacklayout.Children.Add(new Label { Text = "Some Text" });
tcs.SetResult(false);
});
return tcs.Task;
});
}
}
我正在尝试将内容加载到堆栈布局异步但是到目前为止没有运气。
当我浏览页面时,我将元素添加到堆栈布局。即使我在 aysnc 函数上执行它,我也会冻结,直到加载所有内容。我想显示一个 activity 指标。当指示器旋转时,我想加载布局。
我尝试在 OnAppering 方法上执行此操作,但没有成功。
protected async override OnApperaing()
{
base.OnApperaing();
for(int i = 0; i < 100; i++)
{
stacklayout.Children.Add(new Label { Text = "Some Text" });
}
}
我该如何解决这个问题?此致
您在这里没有等待任何方法,因此您的方法同步运行。
你应该会收到警告,字里行间写着什么
The async method lacks await operators...
根据你的情况,你需要做这样的事情
protected async override void OnApperaing()
{
base.OnApperaing();
for(int i = 0; i < 100; i++)
{
await Task.Run(() => {
var tcs = new TaskCompletionSource<bool>();
InvokeOnMainThread(() => {
stacklayout.Children.Add(new Label { Text = "Some Text" });
tcs.SetResult(false);
});
return tcs.Task;
});
}
}