【问题标题】:Xamarin.Forms updating UI thread behaving strangely in iOS & AndroidXamarin.Forms 更新 UI 线程在 iOS 和 Android 中表现异常
【发布时间】:2016-05-27 21:40:55
【问题描述】:

我正在使用异步,等待在按钮单击时更新 UI,以指示用户正在进行一些进度,并且我正在显示加载面板 onclick of button。以下是我的代码:

安卓:

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:

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

               }
    }

Android 和 iOS 共享相同的表单代码。但是对于这种特殊情况,它有条件地工作。 iOS 在添加Task.Delay(40) 和评论Task.Run(() =&gt; {}); 线程后工作。

为什么会这样?但是,如果我在 Android 中进行上述修改,它就不起作用。到底发生了什么?

【问题讨论】:

    标签: c# async-await xamarin.forms


    【解决方案1】:

    您以某种方式阻止了 UIThread,Xamarin 论坛上有很多关于此的问题:

    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/41229/best-practise-waiting-and-synchronising-threads

    您似乎在 View 类中执行此操作,您应该在 ViewModel 中执行此操作,根据经验,我鼓励您不要等待任务,除非完全有必要,否则您应该使用绑定让用户有什么事情发生了!

    大部分都由亚当回答

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      相关资源
      最近更新 更多