【问题标题】:Why is this task await leaving the UI context in Xamarin iOS?为什么此任务等待在 Xamarin iOS 中离开 UI 上下文?
【发布时间】:2019-12-18 09:12:28
【问题描述】:

以下内容在某种程度上动摇了我基于 async/await 的信念系统。在 Xamarin/iOS 下,以下失败,表示 UI 相关的事情正在非 UI 线程中完成。添加检查点表明上下文确实在异步文件写入之后切换。

我的理解是缺少一个ConfigureAwait,下面的应该是完全安全的。我假设这是我不知道的 Xamarin 细微差别,但很难理解这可能是什么。

同样的代码在 Android 和 UWP 上运行良好。

private async void ShareButton_OnClicked(object sender, EventArgs e)
{
    if (!(BindingContext is PhotoViewModel photoViewModel))
    {
        return;
    }

    // in UI context

    var name = photoViewModel.Name ?? "temp.jpg";
    var file = Path.Combine(FileSystem.CacheDirectory, name);

    using (var stream = new FileStream(file, FileMode.Create, FileAccess.Write))
    {
        await stream.WriteAsync(photoViewModel.Data, 0, photoViewModel.Data.Length);
    }

    // not in UI context!

    // calling this causes SIGABRT: UIKit Consistency error
    await Share.RequestAsync(new ShareFileRequest(new ShareFile(file)));
}

【问题讨论】:

  • await 之前检查SynchronizationContext.Current 的值。 Xamarin 应该在启动事件处理程序之前进行设置,以便 await 在 UI 上下文中恢复。
  • @StephenCleary 当你说检查值时,我不确定我在寻找什么。我确实尝试调用 MainThread.IsMainThread(一个 Xamarin Essentials 的东西,似乎在 iOS 上包装了 NSThread),这在之前是真的,之后是假的。在这两种情况下,当前上下文都不为空,但我不知道除此之外还要寻找什么。谢谢。
  • 查看是不是null,如果不是,是什么类型。
  • 在它之前和之后都不为空并且类型为 UIKit.UIKitSynchronizationContext
  • 那么您应该跟进 Xamarin 团队。

标签: ios xamarin async-await


【解决方案1】:

调用它会导致 SIGABRT: UIKit 一致性错误

await Share.RequestAsync(new ShareFileRequest(new ShareFile(file)));

虽然在Android和UWP中都没有问题,但在iOS中可能不兼容这样的写法。上面的代码需要 UI 线程来调用,但是它在 async 方法 ShareButton_OnClicked 中。可能需要专门从主线程调用它,试试下面的代码来调用它。

await Device.InvokeOnMainThreadAsync(() =>
{
    // inkoke your code .
    Share.RequestAsync(new ShareFileRequest(new ShareFile(file)));
});

【讨论】:

  • 这是我最终使用的,但我不明白为什么在 iOS 中无法正确设置上下文。简而言之,为什么这是必要的,我怎么知道这不会突然在其他处理程序中开始发生?
  • @Jeff 我已经用sample code 签入了我的项目,没有问题。我想知道您的项目是否使用最新版本的 VS(16.3.10) / Forms(4.3.0.991221) 和 Essentials (1.3.1)。
  • 我开始认为这只是某种奇怪的 Xamarin 错误
【解决方案2】:

这原来是单声道的一个错误

https://github.com/mono/mono/issues/16759

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-02
    • 2021-04-09
    • 2020-04-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2017-11-11
    相关资源
    最近更新 更多