即使我使用异步方法,为什么UI变得无响应?

时间:2014-05-26 22:58:39

标签: c# android multithreading xamarin

我目前正在使用Xamarin框架开发Android应用,所以我用c#编写它。在这个应用程序中,我从REST-api中获取数据,如下所示:

//Method implemented from interface IOnScrollListener
public async void OnScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
  //lots of other stuff that's not important for this example
  List<Message> messageList = await PopulateMessagebox(arg1, arg2));
}

当您到达列表的底部(因此是IOnScrollListener实现)时,将调用该方法。然而;当我到达底部时屏幕冻结,并且正在调用该方法。考虑到我正在使用ansync方法调用,我很好奇这是怎么回事?不应该在另一个线程上运行,允许主线程不间断/不必等待吗?

我将如何解决此问题,以便应用程序在后台从API获取其他信息时能够做出响应?

编辑:这是populateMessageBox-method

public async Task<List<Message>> PopulateMessagebox(Constants.MMBType type, int skipSize)
    {
        string messagesJson = await _dal.GetMessageBox(type, skipSize, url);
        var mess = new List<Message>();

        try
        {
            if (!string.IsNullOrEmpty(messagesJson))
            {
                mess = Serializer.DeserializeMessagebox(messagesJson);
            }
        }
        catch (Exception e)
        {
            Logger.Logg("Failed to de-serialize the messagebox:" + e);
            throw new AppException(ErrorMessages.SerializationError);
        }
        return mess;
    }

public async Task<string> GetMessageBox(Constants.MMBType type, int skipSize, string url)
        {
            return await GetMessageBoxJSON(type, skipSize, url);

        }

-

private async Task<string> GetMessageBoxJSON(Constants.MMBType type, int skipSize, string url)
        {
            string res = null;

            if (type == Constants.MMBType.Messagebox)
            {
                string param = string.Format("?$filter=Status ne '{0}' and Status ne '{1}'&$skip={2}",
                    Constants.NO.Nob.Status.Sent, Constants.NO.Nob.Status.SentCorres, skipSize);

                string request = url + param;

                res = await DownloadAndHandle(request);
            }

还有几个这样的电话,我们来到这里:

protected virtual async Task<string> SetupAndDownloadString(string uri)
        {
            string responseText;

            if (Session.CookieJar.Size() > 0)
            {
                var client = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Get, uri);
                request.Headers.Add("ApiKey", AppContext.ApiKey);
                request.Headers.Add("Accept", Constants.ApiFormat);
                request.Headers.Add("Cookie", Session.CookieJar.ToString());

                HttpResponseMessage response = await client.SendAsync(request);
                responseText = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                throw new AppException(ErrorMessages.InsufficientAuthorization);
            }

            return responseText;
        }

0 个答案:

没有答案