本文介绍了Xamarin.Forms - 异步操作的 BeginInvokeOnMainThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉使用 Device.BeginInvokeOnMainThread 在 UI 线程上更新 UI 元素的规则,但是我有一个操作需要在 UI 线程上运行,实际上是一个任务.

I am familiar with the rules about updating UI elements on the UI thread using the Device.BeginInvokeOnMainThread, however I have an operation that needs to be run on the UI thread that is actually a Task.

例如,XLabs.Forms.Mvvm 上的 Push/PopAsync 方法在 iOS 上的行为似乎不正确,除非它们在 UI 线程上被调用.Acr.UserDialogs 库中还有另一个示例,用于显示吐司等.

For example, the Push/PopAsync methods on XLabs.Forms.Mvvm seem to behave incorrectly on iOS unless they are invoked on the UI thread. There is also another example in the Acr.UserDialogs library for displaying toasts etc.

我知道使 Action 异步基本上是创建一个异步 void lambda 并且在异常情况下冒着创建死锁的风险,显然我不希望这种情况发生.

I know that making an Action async is basically creating an async void lambda and runs the risk of creating a deadlock in the case of an exception, obviously I don't want this to happen.

是否有人在 UI 线程上执行异步操作而不涉及将 Action 标记为异步的解决方法?

Does anybody have a workaround for performing async operations on the UI thread that doesn't involve marking the Action as async?

推荐答案

只要确保您处理 Action 中的异常就可以了.当您处理异常时,就会出现您描述的问题.下面是从主线程运行异步方法的一个非常简单的示例.

Just make sure you handle exceptions in your Action and you should be fine. The problem you described occurs when you don't handle the exceptions. Below is a very simple example of running an async method from the main thread.

private void Test()
{
    Device.BeginInvokeOnMainThread(SomeMethod);
}

private async void SomeMethod()
{
    try
    {
        await SomeAsyncMethod();
    }
    catch (Exception e) // handle whatever exceptions you expect
    {
        //Handle exceptions
    }
}

private async Task SomeAsyncMethod()
{
    await Navigation.PushModalAsync(new ContentPage());
}

这篇关于Xamarin.Forms - 异步操作的 BeginInvokeOnMainThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:09