我是异步编程的新手
我在node.js上读过一篇关于聊天的文章,我尝试用asp.net mvc异步控制器实现类似的东西
public void RecieveAsync()
{
var list = (List<AsyncCallback>)HttpContext.Application["callbacks"];
var tt = new AsyncCallback((message) =>
{
AsyncManager.Parameters["result"] = message;
});
list.Add(tt);
HttpContext.Application["callbacks"]=list;
while(!AsyncManager.Parameters.ContainsKey("result"))
{
System.Threading.Thread.Sleep(500);
}
}
public JsonResult RecieveCompleted(Message result)
{
var a = new { name = result.name, result.message };
return Json(a, JsonRequestBehavior.AllowGet);
}
public void SendAsync(Message _message)
{
Dictionary<string,object> dict= new Dictionary<string,object>();
var list = (List<AsyncCallback>)HttpContext.Application["callbacks"];
foreach (var elem in list)
{
elem.Invoke(_message);
}
HttpContext.Application["callbacks"] = new List<AsyncCallback>();
dict.Add("ok",true);
AsyncManager.Parameters["result"] = dict;
}
public JsonResult SendCompleted(object result)
{
return Json(result, JsonRequestBehavior.AllowGet);
}
它的工作但仍然有这条线:
while(!AsyncManager.Parameters.ContainsKey("result"))
{
System.Threading.Thread.Sleep(500);
}
它不是非常异步,我还能做什么,如何通过休眠来实现它,并使用相同的逻辑使我的代码更清晰?