.NET服务端持续输出信息到客户端

由于有时查询内容时间长,可以将查询内容逐一显示出来,以达到用户可以提前查看部分内容的形式来提高用户的体验,那么asp.net如何实现连续不断向客户端显示内容?

首先在此,我们不讨论客户端Ajax拉拽的方式解决此问题!提供如下两种方式:

方式一(推荐使用):

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
#region 命名空间

using System.Threading;
using System.Text;

#endregion

namespace ContinuousExport
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //由于asp.net持续输出到客户端
            //注意:(IE内核浏览器)下需要字符达到256个字符以上(可以提前输出样式,控制后面信息样式)
            //才能想客户端即时发送新的信息
            StringBuilder sbResponse = new StringBuilder();
            sbResponse.Append("<style type=\"text/css\">span{color:Red;}</style>");
            while (sbResponse.Length < 257)
            {
                sbResponse.Append(" ");
            }
            Response.Write(sbResponse.ToString());
            Response.Flush();
            int j = 0;
            while (true)
            {
                j++;
                Response.Write("<span>" + j + "</span>\t");
                Response.Flush();
                //1秒输送一次(模拟复杂计算耗时)
                Thread.Sleep(1000);
            }
        }
    }
}

显示效果截图如下:

浏览器:搜高高速浏览器(兼容模式)--兼容模式为IE内核浏览器

效果:每隔一秒钟显示一个数字的效果--此时页面仍然在加载状态

 

 

方式二(不推荐,原因:使用重载Render方法,不能在继续对服务器控件指定相关信息,如赋值等...):

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
#region 命名空间

using System.Threading;
using System.Text;

#endregion

namespace ContinuousExport
{
    public partial class ExportMain : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            //输出后面信息的样式
            Response.Write("<style type=\"text/css\">span{color:Red;}</style>");
            Response.Flush();
            int j = 0;
            while (true)
            {
                j++;
                Response.Write("<span>" + j + "</span>\t");
                Response.Flush();
                //1秒输送一次(模拟复杂计算耗时)
                Thread.Sleep(1000);
            }
        }
    }
}

显示效果如上图。

附上源码:ContinuousExport.zip

作者:曾庆雷
出处:http://www.cnblogs.com/zengqinglei
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明, 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利

 

  

转载于:https://www.cnblogs.com/zengqinglei/archive/2012/10/31/2748946.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值