I use a REST-Services which needs Bacis-Authentication on the following way:
private void button1_Click(object sender, EventArgs e) {
try {
var url = "http://172.34.1.111:8088/ustrich/rest/projects/pid/1234";
using (var wc = this.CreateWebClient(url)) {
var stopWatch = new Stopwatch();
stopWatch.Start();
var s = wc.DownloadString(url);
stopWatch.Stop();
this.label1.Text = stopWatch.Elapsed.ToString();
this.textBox1.Text = s;
}
} catch (Exception ex) {
this.textBox1.Text = ex.ToString();
}
}
protected WebClient CreateWebClient(string url) {
var webClient = new WebClient();
var cache = new CredentialCache { { new Uri(url), "Basic", new NetworkCredential("rest", "rest") } };
webClient.Credentials = cache;
webClient.Headers.Add("Content-Type", "text/xml; charset=utf-8");
webClient.Encoding = Encoding.UTF8;
return webClient;
}
The problem is now, when I start my Test-Application and execute this code, the first time it takes about 5 seconds on wc.DownloadString(url). The follow calls, when I click the second etc. time on the button, it takes only 300ms.
Now my question: Is there something wrong in my code? Can I optimize something there to resolve the problem that it takes 5 seconds on first call?
Thanks for your help.
The first time you hit the code, it gets precompiled. It will always be slow this time. I believe you can use MSBUILD to do this when you build your code but that’s just transferring the time to a different part of the process. In production, this will only happen each time the worker process restarts.