【发布时间】:2015-09-23 12:37:32
【问题描述】:
我有一个 Windows 服务,它使用 WebClient 将 json 数据发送到 MVC5 WebAPI。 Windows Service 和 WebClient 目前都在同一台机器上。
在以每秒大约 10 个请求的速度运行了大约 15 分钟后,每个帖子需要不合理的时间才能完成。它可以从大约 3 毫秒开始完成一个请求,然后累积到大约 5 秒,这对我的应用程序来说太长了。
这是我正在使用的代码:
private WebClient GetClient()
{
var webClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/json");
return webClient;
}
public string Post<T>(string url, T data)
{
var sw = new Stopwatch();
try
{
var json = JsonConvert.SerializeObject(data);
sw.Start();
var result = GetClient().UploadString(GetAddress(url), json);
sw.Stop();
if (Log.IsVerboseEnabled())
Log.Verbose(String.Format("json: {0}, time(ms): {1}", json, sw.ElapsedMilliseconds));
return result;
}
catch (Exception)
{
sw.Stop();
Log.Debug(String.Format("Failed to send to webapi, time(ms): {0}", sw.ElapsedMilliseconds));
return "Failed to send to webapi";
}
}
请求的结果对我来说并不重要。
序列化数据大小从几个字节到大约 1 kB 不等,但这似乎不会影响完成请求所需的时间。
接收请求的 api 控制器几乎立即完成执行(0-1 毫秒)。
从关于 SO 的各种问题和一些博客文章中,我看到有人建议使用 HttpWebRequest 来控制请求的选项。
使用HttpWebRequest 我尝试了这些不起作用的东西:
- Setting the proxy to an empty proxy.
- Setting the proxy to
null - Setting the ServicePointManager.DefaultConnectionLimit to an arbitrary large number.
- 禁用
KeepAlive(我不想这样做,但有人建议这样做)。 - 根本没有打开响应流(有一些影响,但还不够)。
为什么请求需要这么长时间?非常感谢任何帮助。
【问题讨论】:
-
你确定是 .NET 在做这个吗?你能通过另一个工具来模拟和重现行为吗?你的意思是客户端和网络服务在同一台机器上?会不会是你的socket没了,代码还要等待一个空闲的socket?
-
请检查这是否与您的问题无关:support.microsoft.com/en-us/kb/324270 前几天我的 Windows 2003 Server 由于这个安全功能而断开了两个进程之间的 localhost 连接。
-
@CodeCaster 是的,客户端和网络服务在同一台机器上。如何检查我是否没有插座?
标签: c# json asp.net-mvc post webclient