为什么我不能重复使用WebClient来做两次相同的请求?

Bra*_* Ds 5 .net c# wcf webclient

所以代码:

        const long testCount = 2;
        const string jsonInput = "{\"blockId\":\"1\",\"userId\":\"{7c596b41-0dc3-45df-9b4c-08840f1da780}\",\"sessionId\":\"{46cd1b39-5d0a-440a-9650-ae4297b7e2e9}\"}";

        Stopwatch watch = Stopwatch.StartNew();

        using (var client = new WebClient())
        {
            client.Headers["Content-type"] = "application/json";
            client.Encoding = Encoding.UTF8;

            for (int i = 0; i < testCount; i++)
            {
                var response = client.UploadString("http://localhost:8080/BlocksOptimizationServices/dataPositions", "POST", jsonInput);
            }

            watch.Stop();
            double speed = watch.ElapsedMilliseconds / (double)testCount; 
            Console.WriteLine("Avg speed: {0} request/ms", testCount);
Run Code Online (Sandbox Code Playgroud)

对于性能测试,我只想client.UploadString("http://localhost:8080/BlocksOptimizationServices/dataPositions", "POST", jsonInput)多次打电话.但在第一次请求之后总是失败了

"远程服务器返回错误:(400)错误请求."

如果我处理WebClient并重新创建 - 工作,但这会增加额外的性能损失..为什么我不能重复使用WebClient两次?

Ste*_*ong 9

每次请求后都会清除WebClient标头.要自己查看,可以添加一些Debug.Assert()语句.这与第二个请求中的"(400)错误请求"错误一致:

for (int i = 0; i < testCount; i++)
{
      Debug.Assert(client.Headers.Count == 1); // Content-type is set   
      var response = client.UploadString("http://localhost:8080/BlocksOptimizationServices/dataPositions", "POST", jsonInput);    
      Debug.Assert(client.Headers.Count == 0); // Zero!
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以更改代码以每次设置标头:

using (var client = new WebClient())
{            
    for (int i = 0; i < testCount; i++)
    {
        client.Headers["Content-type"] = "application/json";
        client.Encoding = Encoding.UTF8;

        var response = client.UploadString("http://localhost:8080/BlocksOptimizationServices/dataPositions", "POST", jsonInput);
    }
Run Code Online (Sandbox Code Playgroud)

如果我处理WebClient并重新创建 - 工作,但这会增加额外的性能损失..为什么我不能重复使用WebClient两次?

这是一个SO线程似乎并不认为每个请求实例化一个WebClient是一个性能损失:WebClient构造开销

祝好运!