ASP.NET实现HTTP长轮询(四)——WebApi

        本文主要描述如何在ASP.NET WebApi中实现长轮询:

(1)控制器:

using System;
using System.Web.Http;
using System.Threading.Tasks;
using System.Threading;

public class LongPollingController : ApiController
{
        [NonAction]
        private BaseResponse GetData(object state, BaseRequest request)
        {
            BaseResponse response = new BaseResponse();

            int nowTimes = 0;//当前循环次数(或使用Stopwatch计算时间,超时即退出)
                        int maxTimes = 60;//最大循环次数(或使用Stopwatch计算时间,超时即退出)
                        while (++nowTimes <= maxTimes)//(或使用Stopwatch计算时间,超时即退出)
                        {
                            //判断是否已有新数据,若已有则退出循环
                            Thread.Sleep(100);
                        }
                        
            return response;
        }

        [HttpPost]
        public BaseResponse GetData(BaseRequest request)
        {
            Task<BaseResponse> task = new Task<BaseResponse>(new Func<object, BaseResponse>((state) => { return GetData(state, request); }), null);
            task.Start();
            return task.Result;
        }
}

(2)使用jQuery发送请求:

(function getData() {
    $.post('LongPolling/GetData', {}, function(data) {
        //接收并处理数据
        getData();
    });
})();
posted @ 2019-06-10 18:18  竹林之风  阅读(265)  评论(0编辑  收藏  举报