title: entity framework, wait for results
body: <p>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")</p>
  
  <p>How do I best 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.</p>
  
  <p>So how do I convert my code to not tie up asp.net threads, and to respond once results are available?</p>
  
  <pre><code>[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 &gt; 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 &amp;&amp; cycles-- &gt; 0)
          {
              System.Threading.Thread.Sleep(1000);
          }
          return Json(afterEvents.ToArray(), JsonRequestBehavior.AllowGet);
      }
  }
  </code></pre>