2016-12-09 63 views
3

我在webclient類中發現了一個奇怪的行爲。當我使用UploadValues()同步方法時,我通常會得到響應uri,但是當我使用異步版本UploadValuesTaskAsync()到同一個url時,它會將響應uri作爲null返回。爲什麼?Webclient沒有得到迴應uri

實施例:

using (var client = new CustomWebClient()) 
{ 
    await Get(client); 
    Get(client); 
} 

private async Task GetAsync(WebClient client) 
{ 
     var resAsync = await client.UploadValuesTaskAsync("http://address.com", requestData); 
     //client.ResponseUri null here 
} 

private void Get(WebClient client) 
{ 
    var res= client.UploadValues("http://address.com", requestData); 
    //client.ResponseUri **not** null here 
} 

GetAsync方法client.ResponseUri來自空,非空的UploadValues

編輯:

我發現WebClient的是 「定製」:

因此類:

public class CustomWebClient : WebClient 
{ 
    public CookieContainer Cookies { get; private set; } 
    public Uri ResponseUri { get; private set; } 

    public CustomWebClient() 
    { 
     Cookies = new CookieContainer(); 
    } 

    protected override WebRequest GetWebRequest(Uri address) 
    { 
     var request = base.GetWebRequest(address) as HttpWebRequest; 
     if (request == null) 
     { 
      return base.GetWebRequest(address); 
     } 
     request.CookieContainer = Cookies; 
     return request; 
    } 

    protected override WebResponse GetWebResponse(WebRequest request) 
    { 
     var response = base.GetWebResponse(request); 
     ResponseUri = response.ResponseUri; 
     return response; 
    } 
} 

我查了一下,在synchronous方法它擊中前GetWebResponse方法持續到下一行。但在asynchronous版本,它從來沒有打到GetWebResponse

+0

你可能想改變你的GetAsync只是無效是兩個實例之間是一致的 –

+1

它不是一個很好的做法,從異步返回void方法 – gog

+0

你究竟在哪裏閱讀ResponseUri? – JuanR

回答

1

你的定製類僅重寫行爲同步WebResponse GetWebResponse(WebRequest request)方法。

您需要添加替代的異步版本:

protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result) 
{ 
    var response = base.GetWebResponse(request, result); 
    ResponseUri = response.ResponseUri; 
    return response; 
}