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
1.9k views
in Technique[技术] by (71.8m points)

.net - C# How to set HttpClient Keep-Alive to false

I had a low performance problem with HTTP requests on .NET. The HTTP GET request to a REST API on the localhost took about 500 ms to complete. I spent a lot of time to fix it. I have tried many ways: HttpClient, HttpWebRequest, WebClient and RestSharp. None of them work. Most solutions on the Internet said to set Proxy parameter to null but it still won't work faster.

The only way I found to reduce this time is to set the Keep-Alive parameter of request to false:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.KeepAlive = false;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

This works great. Time is reduced to 7-10 ms. But now in some reasons I need to use HttpClient instead of HttpWebRequest. And I can't find how to set Keep-Alive to false for HttpClient. The only thing I found is how to set it to true by setting a "connection" header to "Keep-Alive".

I am using this code for POST request by HttpClient:

        HttpClient _http = new HttpClient();
        _http.DefaultRequestHeaders.Accept.Clear();
        _http.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
        _http.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");

        var content = new StringContent(
            request, Encoding.UTF8, "application/%appname%+xml");
        content.Headers.ContentType.Parameters.Add(
            new NameValueHeaderValue("type", "payload"));

        HttpResponseMessage response = await _http.PostAsync(uri, content);

And it still takes about 500-600 ms to complete.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you set HttpWebRequest.KeepAlive = true the header set is Connection: keep-alive

When you set HttpWebRequest.KeepAlive = false the header set is Connection: close

So you will need

_http.DefaultRequestHeaders.Add("Connection", "close");

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

...