c# - 为什么我不能重用 WebClient 两次发出相同的请求?

标签 c# .net 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);

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

"The remote server returned an error: (400) Bad Request."

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

最佳答案

WebClient header 在每次请求后被清除。要亲自查看,您可以添加几个 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!
}

因此,您可以更改代码以每次都设置 header :

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);
    }

If I dispose WebClient and recreate - works, but this add extra performance penalty.. why I can't reuse WebClient twice?

这是一个 SO 线程,它似乎不认为为每个请求实例化一个 WebClient 会造成很大的性能损失:WebClient construction overhead

祝你好运!

关于c# - 为什么我不能重用 WebClient 两次发出相同的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35703777/

相关文章:

c# - 为什么这个 INSERT 命令不起作用?

c# - WCF -> ILM -> Web 服务 -> SQL Server

c# - WCF、声明、ADFS 3.0

c# - 在 Xamarin 中,我是否应该担心在 ScrollView 中显示大量内容?

C# 后台 worker 划分

c# - 使用 WIA 自动进纸器扫描仪扫描第二页失败

c# - 有哪些调试超时的好方法? (C#)

WCF 捕获异常 "The server did not provide a meaningful reply.."

c# - 获取 C# aspx 项目的用户并查找当前用户。

c# - 通过字符串的值访问类中的变量