当前位置: 首页 > 知识库问答 >
问题:

跳过了524帧!应用程序可能在其主线程上做了太多工作

姬魁
2023-03-14

我正在用这个功能为Android应用程序编码:

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.conversation_list_activity);
        listViewConversationList = FindViewById<ListView>(Resource.Id.listViewConversationPreview);

        string url = ConstantManager.HOST;
        HttpClient oHttpClient = new HttpClient();


        var oTaskGetAsync = oHttpClient.GetAsync(new Uri(url));
        oTaskGetAsync.ContinueWith((oHttpResponseMessage) =>
        {
            var result = oHttpResponseMessage.Result.Content.ReadAsStringAsync().Result;
            listConversationPreview = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ConversationPreview>>(result);
            ConversationAdapter adapter = new ConversationAdapter(this, listConversationPreview);
            RunOnUiThread(() => listViewConversationList.Adapter = adapter);
            listViewConversationList.ItemClick += listViewConversationList_ItemClick;
        });

    }

我成功地运行了它,但在我为Android支持设计导入了一些Nuget软件包之后,现在它抛出了这样一条消息。

我/编舞(1962):跳过了524帧!应用程序可能在其主线程上做了太多工作。

你能告诉我我做错了什么吗?

共有2个答案

邹高懿
2023-03-14

您可以使用处理程序和操作在Android活动中执行异步操作,因此它们不会使用UI线程。

例子:

protected override void OnResume()
{
    base.OnResume();
    Handler handler = new Handler();
    Action action = async delegate { await UpdateListView(); };
    handler.Post(action);
}

private async Task UpdateListView()
{
    //Get data from internet with async methods here and update the ListView
}
柯曜文
2023-03-14

为什么不将整个异步调用封装在它自己的任务中?虽然我会将其分为服务,但为了简单起见,我会这样做:

protected override async void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.conversation_list_activity);
    listViewConversationList = FindViewById<ListView>(Resource.Id.listViewConversationPreview);
    await Task.Run(async() => {
        string url = ConstantManager.HOST;
        HttpClient oHttpClient = new HttpClient();
        string resultString = oHttpClient.GetAsStringAsync(new Uri(url));
        listConversationPreview = 
            Newtonsoft.Json.JsonConvert.DeserializeObject<List<ConversationPreview>>(resultString);
        ConversationAdapter adapter = new ConversationAdapter(this, listConversationPreview);
        RunOnUiThread(() => listViewConversationList.Adapter = adapter);
        listViewConversationList.ItemClick += listViewConversationList_ItemClick;
    }
}

一些旁注:当在生命周期方法(oncreate等)中运行像这样的异步东西时,请记住其他生命周期方法仍将被处理,例如OnResume可能会在OnCreate完成之前执行-这可能会导致一些难以调试的非常奇怪的问题。

在本例中,您可能需要WebAPI NUget包

 类似资料: