2013-01-07 62 views
5

大多數自定義請求屬性的HttpClientHandler定義,這個類是HttpMessageHandler一個子類,類定義是這樣的:其中SendAsync方法時的HttpClientHandler傳遞給HttpClient的被稱爲

public abstract class HttpMessageHandler : IDisposable 
{ 
    protected internal abstract Task<HttpResponseMessage> SendAsync 
    (HttpRequestMessage request, CancellationToken cancellationToken); 
    public void Dispose(); 
    protected virtual void Dispose (bool disposing); 
} 

<C#5.0 in a nutshell>表示在調用HttpClientSendAsync方法時調用中的SendAsync方法。但是HttpClient類也定義了一個SendAsync方法,當我們調用HttpClient的實例時,調用SendAsync這個方法?

+2

總結你的問題:HttpClient的有一個方法SendAsync。 HttpMessageHandler有一個方法SendAsync(由HttpClientHandler覆蓋)。 HttpClient.SendAsync調用HttpMessageHandler.SendAync。有什麼問題? – dtb

+0

你的意思是HttpClient.SendAsync調用HttpMessageHandler的SendAsync方法,而不是它自己的? – Allen4Tech

+0

當您調用HttpClient.SendAsync時,則執行HttpClient.SendAsync。當執行HttpClient.SendAsync時,它會調用HttpMessageHandler.SendAsync。 – dtb

回答

4

這是發生了什麼本質:

HttpMessageInvoker &的HttpClient

class HttpMessageInvoker 
{ 
    private HttpMessageHandler handler; 

    public HttpMessageInvoker(HttpMessageHandler handler) 
    { 
     this.handler = handler; 
    } 

    public virtual void SendAsync() 
    { 
     Console.WriteLine("HttpMessageInvoker.SendAsync"); 
     this.handler.SendAsync(); 
    } 
} 

class HttpClient : HttpMessageInvoker 
{ 
    public HttpClient(HttpMessageHandler handler) 
     : base(handler) 
    { 
    } 

    public override void SendAsync() 
    { 
     Console.WriteLine("HttpClient.SendAsync"); 
     base.SendAsync(); 
    } 
} 

HttpMessageHandler & HttpClientHandler

abstract class HttpMessageHandler 
{ 
    protected internal abstract void SendAync(); 
} 

class HttpClientHandler : HttpMessageHandler 
{ 
    protected internal override void SendAync() 
    { 
     Console.WriteLine("HttpClientHandler.SendAsync"); 
    } 
} 

所以,如果你SendAsyncHttpClient實例上,該方法被執行。該方法從HttpMessageInvoker調用SendAsync方法。該方法調用HttpMessageHandler實例的SendAsync方法。 HttpMessageHandler是抽象的; HttpClientHandler通過覆蓋它來提供抽象SendAync方法的具體實現。

例子:

var handler = new HttpClientHandler(); 
var client = new HttpClient(handler); 
client.SendAsync(); 

輸出:

 
HttpClient.SendAsync 
HttpMessageInvoker.SendAsync 
HttpClientHandler.SendAsync 
相關問題