[英]Xamarin.Forms updating UI thread behaving strangely in iOS & Android
I am using async, await to update UI on button click to indicate user that some progress is going on and I am showing loading panel onclick of button. 我正在使用异步,等待按钮点击更新UI,以指示用户正在进行一些进展,我正在显示加载面板上的按钮。 Below is my code: 以下是我的代码:
Android: 安卓:
async void loginButtonGesture_Tapped(object sender, EventArgs e)
{
try
{
DependencyService.Get<Idevice>().StartLoading();
await AsyncUpdateStatus();
}
}
private async Task AsyncUpdateStatus()
{
try
{
await Task.Run(() =>
{
//Device.BeginInvokeOnMainThread is used in places to stop loading the screen
});
}
}
iOS: iOS版:
async void loginButtonGesture_Tapped(object sender, EventArgs e)
{
try
{
DependencyService.Get<Idevice>().StartLoading();
await Task.Delay(40); //Required for iOS, otherwise loading panel is keep on running
await AsyncUpdateStatus();
}
}
private async Task AsyncUpdateStatus()
{
try
{
//await Task.Run(() => Enabling new thread also not working
//Device.BeginInvokeOnMainThread is used in places to stop loading the screen
}
}
Both Android & iOS is sharing same Forms code. Android和iOS都共享相同的表单代码。 But for this particular case its working conditionally. 但对于这个特殊情况,它有条件地工作。 iOS is working after adding Task.Delay(40)
and commenting Task.Run(() => {});
添加Task.Delay(40)
并评论Task.Run(() => {});
后iOS正在运行Task.Run(() => {});
thread. 线。
Why its so? 为什么会这样? But if I do above modification in Android, it is not working. 但是,如果我在Android中进行上述修改,则无法正常工作。 What exactly is happening? 究竟发生了什么?
Somehow you are blocking the UIThread, there are numerous questions on Xamarin Forums about this: 不知怎的,你阻止了UIThread,关于Xamarin论坛有很多问题:
https://forums.xamarin.com/discussion/47019/activity-indicator-inconsistencies https://forums.xamarin.com/discussion/47019/activity-indicator-inconsistencies
https://forums.xamarin.com/discussion/54237/update-uitextview-text-in-code https://forums.xamarin.com/discussion/54237/update-uitextview-text-in-code
https://forums.xamarin.com/discussion/41229/best-practise-waiting-and-synchronising-threads https://forums.xamarin.com/discussion/41229/best-practise-waiting-and-synchronising-threads
And it seems that you are doing this in your View class, you should do this inside your ViewModel, By experience I encourage you to don't wait a Task unless is completely necessary otherwise you should use Bindings to let the user that something is going on! 似乎你在你的View类中这样做,你应该在你的ViewModel中做这个,根据经验,我鼓励你不要等待任务,除非是完全必要的,否则你应该使用Bindings让用户有事情发生上!
Most of them answered by Adam 大多数人都是亚当回答的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.