Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c# - Async JSON Deserialization

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.

 public async Task<List<MyObject>> Load() 
            {
                var tcs = new TaskCompletionSource<List<Myobject>>();
                var client = new RestSharp.RestClient("https://exampleapi.com");
                client.Authenticator = OAuth1Authenticator.ForProtectedResource(
           [...]);
                var request = new RestSharp.RestRequest("examp.json", Method.GET);
                client.ExecuteAsync(request, response =>
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        List_ = new List<MyObject>();
                        List_ = JsonConvert.DeserializeObject<List<MyObject>>(response.Content);
                        tcs.SetResult(List_);
                    }
                    else
                    {
                        MessageBox.Show("Error");
                    }
                });
                return await tcs.Task;        
            }

Specially for this line of code :

List_ = JsonConvert.DeserializeObject<List<MyObject>>(response.Content);

is it really async ? because it seems to block the the UI . Can you tell me how can I make this function properly async ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<List<MyObject>>(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...