0
我有一個Windows服務,使用WebClient
將json數據發送到MVC5 WebAPI。 Windows Service和WebClient都在同一臺機器上。如何從C#中獲得合理的性能WebClient UploadString
運行約15分鐘後,每秒約10個請求,每個帖子花費過長的時間完成。它可以在大約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嗎?你可以通過另一個相同的工具來模擬和重現行爲嗎?你的意思是客戶端和web服務在同一臺機器上?這可能是因爲你沒有套接字,代碼必須等待一個空閒套接字? – CodeCaster
請檢查這是否與您的問題沒有關係:https://support.microsoft.com/en-us/kb/324270有一天,我有我的Windows 2003服務器丟棄兩個進程之間的本地主機連接,因爲此安全功能。 –
@CodeCaster是客戶端和web服務在同一臺機器上。如何檢查我是否脫離插座? –