在 Xamarin Android 中实现异步任务

3

最近,Async Task 似乎是最棘手的实现之一。我实际上不想在这里使用多线程,而是使用 async tasks。在下面的代码中,我已经实现了 async task 来从 firebase 中获取我的数据到我的应用程序中。即使我正在使用 async task,但这就是我在用户界面上所经历的。

我有三个活动。应用程序启动到第一个活动时,用户不会感受到任何形式的延迟。当我从第一个活动导航到第二个活动时,导航抽屉布局会有几秒钟的延迟,然后才会显示第二个活动和第三个活动的数据。之后,在我在三个活动之间导航时,它会稍微流畅一些。(也就是说,只有在从一个活动移动到另一个活动时才会出现延迟,之后就会流畅地移动)。

请注意,当我在 OnResume() 中注释掉 this.refreshAll() 后,它会流畅地移动

我的 Async 实现得好吗?

Activity2

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    fab = FindViewById<FloatingActionButton>(Resource.Id.fab);

    fab.Click += delegate
    {
        LayoutInflater HeroInflater = LayoutInflater.From(this);
        View mView = peaceHeroInflater.Inflate(Resource.Layout.HeroDialog, null);
        Android.Support.V7.App.AlertDialog.Builder alertDialogBuilder = new Android.Support.V7.App.AlertDialog.Builder(this);
        alertDialogBuilder.SetView(mView);

        var HeroName = mView.FindViewById<EditText>(Resource.Id.editText1);
        alertDialogBuilder.SetCancelable(false)
            .SetPositiveButton("Save", async delegate
            {
                Hero hero = new Hero();
                hero.Uid = string.Empty;
                hero.Name = HeroName.Text;    
                var firebase = new FirebaseClient(FirebaseUrl);                         
                var item = await firebase.Child("sometable").PostAsync<PeaceHero>(hero);

                await ReloadData();   
            })  
            .SetNegativeButton("Cancel", delegate
            {
                alertDialogBuilder.Dispose();
            });

        Android.Support.V7.App.AlertDialog alertDialogAndroid = alertDialogBuilder.Create();
        alertDialogAndroid.Show();
    };
}

private async void refreshAll()
{
    await ReloadData();
}

private async Task ReloadData()
{
    var firebase = new FirebaseClient(FirebaseUrl);
    var items = await firebase.Child("sometable").OnceAsync<>();

    foreach (var item in items)
    {
        Hero details = new Hero();
        details.Uid = item.Key;
        details.Name = item.Object.Name;
        add_Hero.Add(details);
    }

    rv.SetLayoutManager(new LinearLayoutManager(this));
    rv.SetItemAnimator(new DefaultItemAnimator());                    
}

protected  override void OnResume()
{ 
    base.OnResume();
    this.refreshAll();
}

更新

private async  Task refreshAll()
        {

            await RefreshData();


        }


 protected async override void OnResume()
        { 
            base.OnResume();
            await refreshAll();

        }

日志

[Mono] AOT: image 'Mono.Security.dll.so' not found: dlopen failed: library "/data/app-lib/com.companyname.peaceapp.peaceapp-130/libaot-Mono.Security.dll.so" not found
[Mono] AOT: image '/usr/local/lib/mono/aot-cache/arm/Mono.Security.dll.so' not found: dlopen failed: library "/data/app-lib/com.companyname.peaceapp.peaceapp-130/libaot-Mono.Security.dll.so" not found
[Mono] Config attempting to parse: 'Mono.Security.dll.config'.
[Mono] Config attempting to parse: '/usr/local/etc/mono/assemblies/Mono.Security/Mono.Security.config'.
[Mono] Assembly Ref addref System[0x86e311a8] -> Mono.Security[0x8792d7e8]: 2
[Mono] Assembly Ref addref Mono.Security[0x8792d7e8] -> mscorlib[0x73d41ac0]: 68
Loaded assembly: Mono.Security.dll [External]
[Mono] Assembly Ref addref System.Net.Http[0x8649e068] -> System.Core[0x7f2bf708]: 9
[Mono] Assembly Ref addref Mono.Android[0x7f1692f0] -> System[0x86e311a8]: 7
Thread started: <Thread Pool> #4
Thread started: <Thread Pool> #5
[Mono] [0x87aecc90] worker starting
Thread started: <Thread Pool> #6
[Mono] [0x87b045b0] worker starting
Thread started: <Thread Pool> #7
[Mono] [0x87ae1a88] worker starting
[Choreographer] Skipped 80 frames!  The application may be doing too much work on its main thread.
[RecyclerView] No adapter attached; skipping layout
[ProgressBar] updateDrawableBounds: left = 72
[ProgressBar] updateDrawableBounds: top = 0
[ProgressBar] updateDrawableBounds: right = 72
[ProgressBar] updateDrawableBounds: bottom = 0
[Mono] [0x87aecc90] hill climbing, change max number of threads 4
[RecyclerView] No adapter attached; skipping layout
[Mono] Assembly Ref addref Mono.Security[0x8792d7e8] -> System[0x86e311a8]: 8
Thread started: <Thread Pool> #8
Thread started: <Thread Pool> #9
[Mono] [0x851329e8] worker starting
Thread started: <Thread Pool> #10
[Mono] [0x85132de0] worker starting
[Mono] Unloading image System.dll [0x851046d8].
[Mono] Image addref System[0x8548b280] -> System.dll[0x86e30720]: 5
[Mono] Config attempting to parse: 'System.dll.config'.
[Mono] Config attempting to parse: '/usr/local/etc/mono/assemblies/System/System.config'.
[Mono] Unloading image System.dll [0x851046d8].
[Mono] Image addref System[0x8548f438] -> System.dll[0x86e30720]: 6
[Mono] Config attempting to parse: 'System.dll.config'.
[Mono] Config attempting to parse: '/usr/local/etc/mono/assemblies/System/System.config'.
[Mono] Unloading image System.dll [0x851046d8].
[Mono] Image addref System[0x854829d8] -> System.dll[0x86e30720]: 7
[Mono] Config attempting to parse: 'System.dll.config'.
[Mono] Config attempting to parse: '/usr/local/etc/mono/assemblies/System/System.config'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for 'java_interop_jnienv_is_assignable_from'.
[Mono] Probing 'java_interop_jnienv_is_assignable_from'.
[Mono] Found as 'java_interop_jnienv_is_assignable_from'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for 'java_interop_jnienv_get_byte_array_region'.
[Mono] Probing 'java_interop_jnienv_get_byte_array_region'.
[Mono] Found as 'java_interop_jnienv_get_byte_array_region'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for 'java_interop_jnienv_set_byte_array_region'.
[Mono] Probing 'java_interop_jnienv_set_byte_array_region'.
[Mono] Found as 'java_interop_jnienv_set_byte_array_region'.
[Mono] The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
[Mono] Unloading image System.Core.dll [0x854f61d0].
[Mono] Image addref System.Core[0x85501bf0] -> System.Core.dll[0x7f2bedb0]: 5
[Mono] Config attempting to parse: 'System.Core.dll.config'.
[Mono] Config attempting to parse: '/usr/local/etc/mono/assemblies/System.Core/System.Core.config'.
[Mono] The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
[Mono] Unloading image System.Core.dll [0x855214c8].
[Mono] Image addref System.Core[0x84ff8888] -> System.Core.dll[0x7f2bedb0]: 6
[Mono] Config attempting to parse: 'System.Core.dll.config'.
[Mono] Config attempting to parse: '/usr/local/etc/mono/assemblies/System.Core/System.Core.config'.
[Mono] [0x851329e8] hill climbing, change max number of threads 5
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for 'java_interop_jnienv_get_static_field_id'.
[Mono] Probing 'java_interop_jnienv_get_static_field_id'.
[Mono] Found as 'java_interop_jnienv_get_static_field_id'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for 'java_interop_jnienv_get_static_object_field'.
[Mono] Probing 'java_interop_jnienv_get_static_object_field'.
[Mono] Found as 'java_interop_jnienv_get_static_object_field'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for 'java_interop_jnienv_call_boolean_method_a'.
[Mono] Probing 'java_interop_jnienv_call_boolean_method_a'.
[Mono] Found as 'java_interop_jnienv_call_boolean_method_a'.
Thread finished: <Thread Pool> #10
[Mono] [0x85132de0] worker finishing
2个回答

0

OnResume()中调用this.refreshAll()可能会造成阻塞。尝试将OnResume()设置为async并等待this.refreshAll()的结果。

protected async override void OnResume()
{ 
    base.OnResume();
    await this.refreshAll();
}

这样做至少可以使 UI 在数据加载时保持响应。我猜测 OnceAsync<>() 可能会在调用之间缓存您的结果(可能仅查找更改),因此在初始调用后需要做的工作要少得多。

请注意,在生命周期事件中放置 async/await 可能会产生意想不到的后果——例如,如果一个 async OnCreate() 方法有一个等待时间较长的调用,OnStart()OnResume() 方法通常会在 OnCreate() 完成之前启动。


它仍然像之前一样滞后,请查看我的更新代码。 - user8120868
你的问题“我的异步实现得好吗?”的答案基本上是肯定的,看起来很好。反问的问题是:你的应用程序是否存在滞后(需要时间来执行某些操作,例如加载数据以显示),或者阻塞(需要时间来执行某些操作+停止用户与可见组件的交互,即感觉像已经崩溃了)?如果是阻塞的话,那么async/await中没有实现某些东西,如果只是滞后(即用户仍然可以滚动、点击应用程序中的按钮等),那么这是文件读取/数据下载代码的问题,而async/await代码是好的。 - Jonathan Twite
如果像你所说的那样实现得很好,那么我为什么会遇到延迟/阻塞问题呢? - user8120868
你遇到了哪个问题?卡顿还是阻塞? - Jonathan Twite
它正在面临滞后问题。用户交互没有停止,在我的日志记录中,我不断看到应用程序可能在其主线程上执行太多工作。 - user8120868

0

可重用的异步任务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace Android.Basic.Core
{
    public class AsyncTasker : AsyncTask<Java.Lang.Void, Java.Lang.Void, Java.Lang.Void>
    {
        private Action Action { get; }
        public event EventHandler<object> TaskCompleted;
        public void NotifyCompletedTask(object result)
        {
            Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(() =>
            {
                this.TaskCompleted?.Invoke(this, result);
            });
           
        }
        public AsyncTasker(Action action)
        {
            this.Action = action;
        }
        protected override Java.Lang.Void RunInBackground(params Java.Lang.Void[] @params)
        {
            if (this.Action == null)
                return null;
            this.Action();
            return null;
        }
    }
}

用法

var asyncTasker = new AsyncTasker(() =>
            {
                //Do non UI task, Use "MainThread.BeginInvokeOnMainThread" to update UI.
                

                //Notify that task completed
                asyncTasker.NotifyCompletedTask(null);

            });
            asyncTasker.TaskCompleted += delegate
            {
                Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(() =>
                {
                    
                     //Do completed task
                });
            };
            asyncTasker.Execute();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接