代码改变世界

一个非常简单的 ASP.NET MVC 示例:长轮询(又叫:反向 AJAX,英文名:Comet)实现

2013-03-26 17:22  音乐让我说  阅读(1662)  评论(0编辑  收藏  举报

关于 长轮询(又叫:反向 AJAX,英文名:Comet)的介绍,请查看:反向Ajax,第1部分:Comet介绍

下面是代码实现:

UI:

<p>
    <input type="button" onclick="longPolling();" value="开始长轮询" />
</p>

<div>
    <p>
        服务器返回的信息:
    </p>
    <p id="msgContainer">
    
    </p>
</div>
<script type="text/javascript">
    function longPolling()
    {
        $.getJSON("@Url.Action("GetTime", "DateTime")", function (json)
        {
            $("#msgContainer").append(json.date + "<br/>");
            longPolling();
        });
    }
</script>

 

后台代码:

public class DateTimeController : AsyncController
{
    public DateTimeController()
    {

    }

    public void GetTimeAsync()
    {
        //计时器,5秒种触发一次Elapsed事件        
        System.Timers.Timer timer = new System.Timers.Timer(5000);
        //告诉.NET接下来将进行一个异步操作       
        AsyncManager.OutstandingOperations.Increment();
        //订阅计时器的Elapsed事件    
        timer.Elapsed += (sender, e) =>
        {
            //保存将要传递给GetTimeCompleted的参数                
            AsyncManager.Parameters["nowdate"] = e.SignalTime;
            //告诉ASP.NET异步操作已完成,进行GetTimeCompleted方法的调用               
            AsyncManager.OutstandingOperations.Decrement();
        };
        //启动计时器       
        timer.Start();
    }

    public ActionResult GetTimeCompleted(DateTime nowdate)
    {
        return Json(new { date = nowdate.ToString("HH:mm:ss") + "  Welecom " }, JsonRequestBehavior.AllowGet);
    }
}

运行效果图:

另一个示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using System.IO;

namespace TestMvc.MvcUI.Controllers
{
    public class ArticleController : AsyncController
    {
        #region 方式 1

        public void ArticleAsync(string name)
        {
            AsyncManager.OutstandingOperations.Increment();
            Task.Factory.StartNew(() =>
                {
                    string path = ControllerContext.HttpContext.Server.MapPath(string.Format(@"\articles\{0}.html", name));
                    using (StreamReader reader = new StreamReader(path))
                    {
                        AsyncManager.Parameters["content"] = reader.ReadToEnd();
                    }
                    AsyncManager.OutstandingOperations.Decrement();
                });
        }

        public ActionResult ArticleCompleted(string content)
        {
            return Content(content);
        }

        #endregion

        #region 方式 2

        public Task<ActionResult> Article(string name)
        {
            return Task.Factory.StartNew(() =>
            {
                string path = ControllerContext.HttpContext.Server.MapPath(string.Format(@"\articles\{0}.html", name));
                using (StreamReader reader = new StreamReader(path))
                {
                    AsyncManager.Parameters["content"] = reader.ReadToEnd();
                }
            }).ContinueWith<ActionResult>(task =>
            {
                string content = (string)AsyncManager.Parameters["content"];
                return Content(content);
            });
        }

        #endregion

        #region 方式 3

        public Task<ActionResult> Article2(string name)
        {
            return Task.Factory.StartNew(() =>
            {
                string path = ControllerContext.HttpContext.Server.MapPath(string.Format(@"\articles\{0}.html", name));
                using (StreamReader reader = new StreamReader(path))
                {
                    return reader.ReadToEnd();
                }
            }).ContinueWith<ActionResult>(task =>
            {
                return Content((string)task.Result);
            });
        }

        #endregion
    }
}

 

查考自:.Net MVC 实现长轮询

谢谢浏览!