1

I have a page waiting for response of a Generic Handler with this javascript code:

if (typeof (EventSource) !== "undefined") {
var source = new EventSource("../Handler/EventHandler.ashx");
source.onmessage = function (event) {
    alert(event.data);
   };
} 

and this handler:

public void ProcessRequest(HttpContext context)
{
        context.Response.ContentType = "text/event-stream";
        context.Response.Write("data: Event handler started");
        context.Response.Flush();
        context.Response.Close();
}

Now I want to have a method (in handler) ,like this to send some real-time data through ashx to my page:

public void send(string data){
    //send through ashx
}

How can I write this method to be callable from other classes? Can I use thread?

Majid
  • 13,853
  • 15
  • 77
  • 113
  • This is exactly the kind of thing that [SignalR](http://signalr.net/) is intended to solve. – mason Jul 25 '14 at 18:00

1 Answers1

2

Your ProcessRequest server side method should never end:

public void ProcessRequest(HttpContext context)
{
    Response.ContentType = "text/event-stream";

    var source = new SomeEventSource();
    source.OnSomeEvent += data =>
    {
        context.Response.Write(data);
        context.Response.Flush();
    }

    while (true)
    {
        System.Threading.Thread.Sleep(1000);
    }

    Response.Close();
}

This being said, using a forever blocking loop in the ProcessRequest method would be terrible in terms of resource consumption. You should absolutely consider using an IHttpAsyncHander instead of an IHttpHandler. This would allow you to free the worker thread while waiting for notifications from the external source.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I don't want to use continuously check, since I'm using Quartz.net to trigger new events.Is it possible without checking? – Majid Jul 25 '14 at 17:04
  • Great, then simply subscribe to the corresponding events that Quartz.NET provides you. The important thing is that you should not return from the ProcessRequest method. It should be running forever. Also make sure that you are using an `IHttpAsyncHandler` if you don't want to kill your webserver. – Darin Dimitrov Jul 25 '14 at 17:07
  • I'm a little beginner, so can you please say how can I use `IHttpAsyncHander` in this issue? – Majid Jul 25 '14 at 17:12
  • 2
    This will depend on the underlying eventing system you are using and whether it supports that. Bear in mind that properly implementing IHttpAsyncHandler is not a trivial task. If you are a beginner you might consider using a ready to use implementation server such as SignalR. – Darin Dimitrov Jul 25 '14 at 17:12