這兩天在使用Asp.net MVC 4開發(fā)COMET消息通知機制,在后端使用異步線程對消息進行訂閱,客戶端通過AJAX長連接請求MVC中的ACTION,如:http://localhost/event/imageSet,即表示獲取ImageSet對象的變更消息(新增,更新和刪除消息)。
public interface IEntityEventTEntity>
{
//變更的實體類對象
TEntity[] Entities
{
get;
}
//操作類型
EntityEventType Type
{
get;
}
}
public enum EntityEventType : int
{
Create = 0,
Update = 1,
Removed = 2
}
[SessionState(SessionStateBehavior.ReadOnly)]
public class EntityEventController : Controller
{
//異步獲取對ImageSet對象操作的變更事件Action,millsecondsTimeout為超時時間。
public async TaskActionResult> ImageSet(int millisecondsTimeout = 10000)
{
return await this.EventAsyncImageSetData>(millisecondsTimeout);
}
private async TaskActionResult> EventAsyncTEntity>(int millisecondsTimeout)
{
IEntityEventTEntity> entityEvent = await EntityEventSubcriber.Instance.WaitForEntityEventTEntity>(millisecondsTimeout);
return this.Json(new
{
HasEvent = null != entityEvent,
EntityEvent = entityEvent
}, JsonRequestBehavior.AllowGet);
}
}
(2) 如果Controller層面應(yīng)用或者Filter中操作過Session,那么為了避免長鏈接時不會導至同一Session在其他調(diào)用中Session Block的情況,需要在Controller頭上加入[SessionState(SessionStateBehavior.ReadOnly)] 的Attribute,來表示當前Controller對Session為只讀操作,這樣就其他操作就不會被阻塞了。
$(document).ready(function () {
var $hoverList = $("#imageSets").hoverList({title:"圖片集列表", selectedIndex: 1 });
var getEvent = function(){
var getPattern = "/EasyshirtBackend/imageSet/0";
$.getJSON("/EasyshirtBackend/event/imageSet/100000" , function(data){
if(data.HasEvent){
//Create
if(data.EntityEvent.Type == 0){
$.each(data.EntityEvent.Entities, function(i, entity){
//TODO: 處理實體類新增
if(i == data.EntityEvent.Entities.length - 1){
getEvent();
}
});
return;
}
//Update
if(data.EntityEvent.Type == 1){
$.each(data.EntityEvent.Entities, function(i, entity){
//TODO: 處理實體類更新
if(i == data.EntityEvent.Entities.length - 1){
getEvent();
}
});
return;
}
//Delete
if(data.EntityEvent.Type == 2){
$.each(data.EntityEvent.Entities, function(i, entity){
//TODO: 處理實體類刪除
if(i == data.EntityEvent.Entities.length - 1){
getEvent();
}
});
}
}else{
$("#imageSets").hoverList("add", data);
getEvent();
}
});
};
getEvent();
});