SSE thread.sleep阻塞其他线程

时间:2015-12-21 11:57:55

标签: asp.net razor server-sent-events thread-sleep

以下简化代码(C#)是SSE的服务器端。当我使用Thread.Sleep()代替Response.Write("retry:10000\n\n")其他ajax请求时,请保持挂起状态。如何创建正确的SSE事件流?

Response.ContentType = "text/event-stream";
DateTime echo;

while (true)
{
    var db = Database.Open("SSE");
    echo = db.QueryValue("select last_change from table");
    db.Close();
    Response.Write(string.Format("data:{1}\n\n", echo.GetHashCode()));

    ///// debug this works 
    Response.Write("retry:10000\n\n");
    Response.Flush();
    Response.Close();
    return;
    /////////// this doesn't work

    Response.Flush();
    if (Response.IsClientConnected == false)
    {
        break;
    }
    System.Threading.Thread.Sleep(10000);

}

P.S。我还计划使用SqlDependency,但尚未想到这一点。

编辑: 我认为问题在于会话状态。

2 个答案:

答案 0 :(得分:0)

为什么你有“回归”;后 Response.Close();

你不忘记删除它吗?

答案 1 :(得分:0)

确实问题在于sessionstate,ASP.net只允许一个活动会话线程。如果将sessionstate设置为off或只读,则应修复它。据我所知,这在剃刀语法中是不可用的,因此我用IReadOnlySessionState创建了一个.ashx。

 public class SSE : IHttpHandler, IReadOnlySessionState
    {

public class SSE : IHttpHandler, IReadOnlySessionState
{

    public void ProcessRequest(HttpContext context)
    {

        context.Response.ContentType = "text/event-stream";
        DateTime echo;
        while (true)
        {
            var db = Database.Open("SSE");
            echo = db.QueryValue("select last_change from table");
            db.Close();
            context.Response.Write(string.Format("data:{0}\n\n", echo.GetHashCode()));
            context.Response.Flush();
            if (context.Response.IsClientConnected == false)
            {
                break;
            }
            System.Threading.Thread.Sleep(10000);

        }

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}