我通过此代码调用我的Web服务,它运行良好。但是,它很慢。 任何想法或其他方式更快地调用Web服务?
WebRequest request = WebRequest.Create("myurl");
request.Method = "POST";
request.Timeout = 5000;
request.Proxy = null;
string data = string.Format("fromidLinhVuc={0}", 0);
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
var dataStream = new StreamWriter(request.GetRequestStream());
dataStream.Write(data);
dataStream.Close();
WebResponse response = request.GetResponse();
return response;
答案 0 :(得分:2)
这可能是您的问题,也可能不是,但您需要using
块:
WebRequest request = WebRequest.Create("myurl");
request.Method = "POST";
request.Timeout = 5000;
request.Proxy = null;
string data = string.Format("fromidLinhVuc={0}", 0);
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
using (var dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(data);
}
WebResponse response = request.GetResponse();
return response;
由于此代码返回实现WebResponse
的{{1}},因此调用者可以在IDisposable
块中调用此代码,以确保using
被称为。
答案 1 :(得分:2)
通过这种或那种方式调用它,无法更快地建立远程Web服务。在任何情况下,您都必须等待响应,这是您无法控制的。所以没办法。
您可以做的事情是,您正在异步调用Web服务,以便在等待服务响应时继续。虽然不完全使网络服务更快,但这可能非常有益,取决于您的具体情况,实际上给人的印象是事情变得更快:
public async GetMyResponseAsync()
{
WebRequest request = WebRequest.Create("myurl");
request.Method = "POST";
request.Timeout = 5000;
request.Proxy = null;
string data = string.Format("fromidLinhVuc={0}", 0);
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
var dataStream = new StreamWriter(request.GetRequestStream());
dataStream.Write(data);
dataStream.Close();
WebResponse response = await request.GetResponseAsync();
return response;
}
然后在你的调用代码中你可能会做某事。像这样
...
// Do stuff
var response = GetMyResponseAsync();
// Do more stuff unrelated to 'response'
// Do stuff with 'response'
...
与response
无关的部分将立即执行,而另一部分将等到response
可用...