Async JSON Deserialization

后端 未结 2 437
無奈伤痛
無奈伤痛 2020-12-11 03:38

I need to do a RestRequest and get some JSON, I am not sure if my method is really async since there is still a little freeze in my UI when I use this method.



        
2条回答
  •  孤城傲影
    2020-12-11 04:18

    It seems the delegate passed as an argument to ExecuteAsync is being executed on the UI thread. If that is the case, simply use Task.Run to run the delegate on the threadpool instead.

    client.ExecuteAsync(request, async (response) =>
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var list = await Task.Run( () => JsonConvert.DeserializeObject>(response.Content));
                tcs.SetResult(list);
            }
            else
            {
                MessageBox.Show("Error");
            }
        });
    

    Is List_ a field? It seems to me like it should be a local variable. Also, there's no need to initialize it with an empty list before deserializing the json.

提交回复
热议问题