Xamarin.Forms-用于异步操作的BeginInvokeOnMainThread [英] Xamarin.Forms - BeginInvokeOnMainThread for an async Action

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

问题描述

我熟悉使用Device.BeginInvokeOnMainThread更新UI线程上的UI元素的规则,但是我有一个操作需要在实际上是Task的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.

例如,除非在UI线程上调用XLabs.Forms.Mvvm上的Push/PopAsync方法,否则它们在iOS上的行为似乎不正确. 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.

有人在不涉及将Action标记为异步的情况下在UI线程上执行异步操作的解决方法吗?

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆