ASP.NET实现HTTP长轮询(一)——WebForm
本文主要描述如何在ASP.NET WebForm中实现长轮询:
(1)在ASP.NET WebForm的aspx文件中设置如下指令即可实现异步的ASP.NET WebForm:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LongPolling.aspx.cs" Inherits="LongPolling" Async="true" AsyncTimeout="60" %>
Async:是否异步WebForm,AsyncTimeout:异步超时时间(秒)。
(2)在aspx.cs文件中实现异步获取数据:
方式一:超过循环次数即退出(或使用Stopwatch计算时间,超时即退出)
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI;
public partial class LongPolling : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//注册异步任务
this.Page.RegisterAsyncTask(new PageAsyncTask(GetData));
}
/// <summary>
/// 获取数据
/// </summary>
/// <returns></returns>
private async Task GetData()
{
int nowTimes = 0;//当前循环次数(或使用Stopwatch计算时间,超时即退出)
int maxTimes = 60;//最大循环次数(或使用Stopwatch计算时间,超时即退出)
while (++nowTimes <= maxTimes)//(或使用Stopwatch计算时间,超时即退出)
{
//判断是否已有新数据,若已有则退出循环并响应
Thread.Sleep(100);
}
}
}
方式二:使用计时器
using System;
using System.Threading.Tasks;
using System.Web.UI;
using System.Timers;
public partial class LongPolling : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//注册异步任务
this.Page.RegisterAsyncTask(new PageAsyncTask(GetData));
}
/// <summary>
/// 获取数据
/// </summary>
/// <returns></returns>
private async Task GetData()
{
int nowTimes = 0;//当前循环次数(或使用Stopwatch计算时间,超时即退出)
int maxTimes = 60;//最大循环次数(或使用Stopwatch计算时间,超时即退出)
//计时器,每1秒种触发一次Elapsed事件
Timer timer = new Timer(1000);
//订阅计时器的Elapsed事件
timer.Elapsed += (sender, e) =>
{
//判断是否已有新数据或超时,若是则停止计时器并响应
};
//启动计时器
timer.Start();
}
}
(3)使用jQuery发送请求:
(function getData() {
$.post('LongPolling.aspx', {}, function(data) {
//接收并处理数据
getData();
});
})();
浙公网安备 33010602011771号