Async Download and Deserialize

前端 未结 2 1042
情深已故
情深已故 2021-01-27 16:28

Good evening,

I am trying to refine some code using async programming and would like to know if the following code is well written or not, and if is there any way to imp

2条回答
  •  暖寄归人
    2021-01-27 17:00

    I am using following code in production without any issues.

    // Creating and disposing HttpClient is unnecessary
    // if you are going to use it multiple time
    // reusing HttpClient improves performance !!
    // do not worry about memory leak, HttpClient
    // is designed to close resources used in single "SendAsync"
    // method call
    private static HttpClient client;
    
    
    public Task DownloadAs(string url){
    
        // I know I am firing this on another thread
        // to keep UI free from any smallest task like
        // preparing httpclient, setting headers
        // checking for result or anything..., why do that on
        // UI Thread?
    
        // this helps us using excessive logging required for
        // debugging and diagnostics
    
        return Task.Run(async ()=> {
    
           // following parses url and makes sure
           // it is a valid url
           // there is no need for this to be done on 
           // UI thread
           Uri uri = new Uri(url);
    
           HttpRequestMessage request = 
              new HttpRequestMessage(uri,HttpMethod.Get);
    
           // do some checks, set some headers...
           // secrete code !!!
    
           var response = await client.SendAsync(request,
               HttpCompletionOption.ReadHeaders);
    
           string content = await response.Content.ReadAsStringAsync();
    
           if(((int)response.StatusCode)>300){
    
               // it is good to receive error text details
               // not just reason phrase
    
               throw new InvalidOperationException(response.ReasonPhrase  
                  + "\r\n" + content);
           }
           return JsonConvert.DeserializeObject(content);
    
        });
    }
    

    ConfigureAwait is tricky, and makes debugging more complicated. This code will run without any issues.

    If you want to use CancellationToken then you can pass your token in client.GetAsync method.

提交回复
热议问题