服務(wù)器端控件帶來(lái)的好外我在這就不多說(shuō)了,但多過(guò)的使用服務(wù)器端件保存控件的狀態(tài)會(huì)帶來(lái)大量的viewstate的情況大家一定遇到過(guò)吧.過(guò)多的viewstate會(huì)很大程度上降低頁(yè)面的加載速度制成服務(wù)器端的性能下降.
以下是結(jié)合csharpziplib對(duì)viewstate進(jìn)行壓縮的方法.
msplus.web.ui.page 源碼:
using system;
using system.web.ui;
using system.io;
using icsharpcode.sharpziplib.zip.compression;
namespace msplus.web.ui
{
/**//// <summary>
/// 壓縮viewstate by mack.z (msplus)
/// </summary>
public class page : system.web.ui.page
{
protected override void savepagestatetopersistencemedium(object pviewstate)
{
losformatter mformat = new losformatter();
stringwriter mwriter = new stringwriter();
mformat.serialize(mwriter, pviewstate);
string mviewstatestr = mwriter.tostring();
byte[] pbytes = system.convert.frombase64string(mviewstatestr);
pbytes = compress(pbytes);
string vstatestr = system.convert.tobase64string(pbytes);
registerhiddenfield("__mspvstate", vstatestr);
}
protected override object loadpagestatefrompersistencemedium()
{
string vstate = this.request.form.get("__mspvstate");
byte[] pbytes = system.convert.frombase64string(vstate);
pbytes = decompress(pbytes);
losformatter mformat = new losformatter();
return mformat.deserialize(system.convert.tobase64string(pbytes));
}
public static byte[] compress(byte[] pbytes)
{
memorystream mmemory = new memorystream();
deflater mdeflater = new deflater(icsharpcode.sharpziplib.zip.compression.deflater.best_compression);
icsharpcode.sharpziplib.zip.compression.streams.deflateroutputstream mstream = new icsharpcode.sharpziplib.zip.compression.streams.deflateroutputstream(mmemory,mdeflater,131072);
mstream.write(pbytes,0,pbytes.length);
mstream.close();
return mmemory.toarray();
}
public static byte[] decompress(byte[] pbytes)
{
icsharpcode.sharpziplib.zip.compression.streams.inflaterinputstream mstream = new icsharpcode.sharpziplib.zip.compression.streams.inflaterinputstream(new memorystream(pbytes));
memorystream mmemory = new memorystream();
int32 msize;
byte[] mwritedata = new byte[4096];
while(true)
{
msize = mstream.read(mwritedata, 0, mwritedata.length);
if (msize > 0)
{
mmemory.write(mwritedata, 0, msize);
}
else
{
break;
}
}
mstream.close();
return mmemory.toarray();
}
}
}
使用方法(aspx.cs頁(yè)面繼承msplus.web.ui.page):public class pageclass : system.web.ui.page
測(cè)試下來(lái)的結(jié)果:壓縮后的viewstate只有原來(lái)的20%!
--------------------------------------------------------------------------------
我作了一個(gè)小小的測(cè)試.先后用同一個(gè)頁(yè)面加密和不加密的情況下,刷新頁(yè)面觀測(cè)w3wp.exe的cpu占用情況.此頁(yè)面的viewstate大小為3.996 bytes
w3wp.exe 以下是每次刷新的時(shí)cpu的情況
05 03 05 03 06 05 05 08 03 05 03 不加密,平均是 4.6
05 05 06 05 05 03 08 02 03 05 06 加密,平均是5.3
新聞熱點(diǎn)
疑難解答
圖片精選