xamarin - 处理异步方法的配置更改

标签 xamarin xamarin.android async-await c#-5.0

我有一个事件,其中有一个异步方法。这种异步方法是长期运行的。在 async 方法返回后,需要更新 UI 和一些控件引用 Activity。
目前,如果您在异步任务运行时没有配置更改(如屏幕旋转),则一切正常。但是,如果在运行时发生配置更改,则会引发异常 Activity is destroyed 并且不会更新 UI。从我所做的阅读来看,这似乎是因为 async 方法捕获上下文,然后尝试更新旧的上下文,旧的上下文当然在配置更改后被破坏。

我的问题是:解决这个问题的最佳方法是什么,或者在最坏的情况下解决这个问题?

最佳答案

我个人认为你只有三个选择

  • 您可以永久或临时禁用轮换,但这是一种不好的做法

  • 永久禁用它 设置配置更改
    [Activity(Label = "...", ConfigurationChanges = Android.Content.PM.ConfigChanges.KeyboardHidden | Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]   
    

    暂时禁用它 在任务工作时,您应该禁用旋转处理,

    禁用
    this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Nosensor;
    

    使能够
    this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Sensor;
    
  • 如果您正在使用片段,您可以使用 RetainInstance = true 防止片段破坏.这可能有效,但我从未测试过。
  • 您可以使用 CancelationToken 取消任务并在 OnRestoreInstanceState() 中重新启动它
    这是如何取消任务的示例
    { CancellationTokenSource cts; ... // If a download process is already underway, cancel it. if (cts != null) { cts.Cancel(); }
    // Now set cts to cancel the current process if the button is chosen again. CancellationTokenSource newCTS = new CancellationTokenSource(); cts = newCTS;
    try { //Send cts.Token to carry the message if there is a cancellation request. await AccessTheWebAsync(cts.Token); } // Catch cancellations separately. catch (OperationCanceledException) { ResultsTextBox.Text += "\r\nDownloads canceled.\r\n"; } catch (Exception) { ResultsTextBox.Text += "\r\nDownloads failed.\r\n"; } // When the process is complete, signal that another process can proceed. if (cts == newCTS) cts = null; }

  • 并且在任务中
    async Task AccessTheWebAsync(CancellationToken ct)
    {
        ...
        // Retrieve the website contents from the HttpResponseMessage.
        byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
    
        // Check for cancellations before displaying information about the 
        // latest site. 
        ct.ThrowIfCancellationRequested();
        ...
    }
    

    关于xamarin - 处理异步方法的配置更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25027276/

    相关文章:

    xamarin - RabbitMQ Client-是否有可移植的类库版本

    android - 有没有办法在 AXML 中通过 DIP 对齐编辑文本中的文本?

    windows-phone-7 - Xamarin Monotouch 是否可以在 Microsoft Windows Phone 移动版上运行?

    .net - 如何用回调包装 3rdParty 函数以便能够等待回调完成然后从回调函数返回结果?

    javascript - 如何在 Observable 方法中顺序调用异步函数?

    c# - 类中的DataSet是否不异步刷新?

    xamarin - 在 AppCenter 中设置 android 应用程序签名时的密码

    android - TabbedPage 中 ListView 中的 Xamarin Forms Slider 无法正确滑动

    c# - Xamarin 的当前上下文中不存在名称 'Log'?

    Android webview 保留以前的页面内容而不重新加载?