我有一个事件,其中有一个异步方法。这种异步方法是长期运行的。在 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/