web service的执行效率是比较低的,所以在调用web方法时应尽量的一次性返回全部数据.同时还可以使用缓存技术.所谓的缓存技术也就是在一段时间内调用相同的方法时并不会执行web方法,而是直接从缓存中拿结果.在.net中可以用CacheDuration特性来修饰web方法,说明该方法使用了缓存.
[ WebMethod(Description="Number of times this service has been accessed",
CacheDuration=60,MessageName="ServiceUsage") ]
public int ServiceUsage()
{
// If the XML Web service has not been accessed, initialize it to 1.
if (Application["MyServiceUsage"] == null)
{
Application["MyServiceUsage"] = 1;
}
else
{
// Increment the usage count.
Application["MyServiceUsage"] = ((int) Application["MyServiceUsage"]) + 1;
}
CacheDuration=60,MessageName="ServiceUsage") ]
public int ServiceUsage()
{
// If the XML Web service has not been accessed, initialize it to 1.
if (Application["MyServiceUsage"] == null)
{
Application["MyServiceUsage"] = 1;
}
else
{
// Increment the usage count.
Application["MyServiceUsage"] = ((int) Application["MyServiceUsage"]) + 1;
}
// Return the usage count.
return (int) Application["MyServiceUsage"];
}
return (int) Application["MyServiceUsage"];
}
上面代码说明在60秒内调用该方法,只会在第一次执行该代码,其余的只会从缓存中取结果.60秒后缓存会清空.除了可以用CacheDuration来实现,还可以使用Cache类来实现.
static int i=0;
[WebMethod]
public int test()
{
i=i+1;
if (HttpContext.Current.Cache["i"]==null)
{
HttpContext.Current.Cache.Add("i",i,null,DateTime.MaxValue,new TimeSpan(6000),CacheItemPriority.Normal,null);
public int test()
{
i=i+1;
if (HttpContext.Current.Cache["i"]==null)
{
HttpContext.Current.Cache.Add("i",i,null,DateTime.MaxValue,new TimeSpan(6000),CacheItemPriority.Normal,null);
// HttpContext.Current.Cache.Add("i",i,null,DateTime.Now.AddSeconds(6),TimeSpan.Zero,CacheItemPriority.Normal,null);这句也可以.
}
else
{
i=Convert.ToInt32(HttpContext.Current.Cache["i"]);
}
return i;
}
}
else
{
i=Convert.ToInt32(HttpContext.Current.Cache["i"]);
}
return i;
}
上面代码中第一次执行时往Cache里添加了一个对象,这个对象在6秒种后被释放.与使用CacheDuration不同的是,即使缓存已经存在了对象,执行该方法时仍然会执行该方法内的代码.