开发者

entity framework, wait for results

I'm writing some code where, most commonly, no results will be returned from a query against Entity Framework. This request has been submitted by some jQuery code, and if I reply with "no results", it's just going to turn around and make the same request again - so I'd like to not respond until either some results are available, or a reasonable amount of time (e.g. 30 seconds) have passed (however, I don't want to cache results for 30 seconds - 30 seconds is a reasonable amount of time to not send a response to the query - if results become available, I want them available "immediately")

How do I bes开发者_开发问答t go about this. I tried sleeping between re-querying, but it a) doesn't seem to be working (every request that starts with no results waits the full 30 seconds), and b) will tie up an asp.net thread.

So how do I convert my code to not tie up asp.net threads, and to respond once results are available?

[HttpGet]
public ActionResult LoadEventsSince(Guid lastEvent, int maxEvents)
{
    maxEvents = Math.Min(50, maxEvents);    //No more than 50
    using (var dbctxt = new DbContext())
    {
        var evt = dbctxt.Events.Find(lastEvent);
        var afterEvents = (from et in evt.Session.Events
                     where et.OccurredAt > evt.OccurredAt
                     orderby et.OccurredAt
                     select new { EventId = et.EventId, EventType = et.EventType, Control = et.Control, Value = et.Value }).Take(maxEvents);

        var cycles = 30;
        while (afterEvents.Count() == 0 && cycles-- > 0)
        {
            System.Threading.Thread.Sleep(1000);
        }
        return Json(afterEvents.ToArray(), JsonRequestBehavior.AllowGet);
    }
}


check out this mix 11 session: "Pragmatic JavaScript jQuery & AJAX with ASP.NET". At the very end of it (about 40-45 minutes into the session) there is a demo right for you.
I'm prety sure you'll say wow..
Damian Edwards promissed to post more about the technique on his blog, but we are yet to see it..


See > Reverse ajax Comet/Polling implementation for ASP.NET MVC?.

You need to go with long polling. It basically sends a request to the server and the server just keeps it in the queue. It accumulates all the queries and as soon as it receives some data it sends the response to each of the queued requests.

EDIT: Also this is interesting > Comet implementation for ASP.NET?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜