Michael J. Gray
Michael J. Gray

Reputation: 9896

Is there a way to delay an HTTP response in ASP.NET MVC 4 without using Thread.Sleep?

I want to delay the response of my website authentication request so that the server begins responding at a particular seconds offset from when the request was received.

For example, if the user authenticates at 04:00:00, I want the response to come back at 04:00:05, not sooner nor later. If it is not possible for the code to meet the deadline, I want it to cause an error.

This must be done on the server side and I would like to avoid using Thread.Sleep. Though, I was thinking there may be a way to do this with an async controller and using Thread.Sleep in part of the request's continuation

Has anyone here faced a similar challenge and what was your solution?

Can any of you folks think of a way to do this while avoiding Thread.Sleep and maintaining responsiveness?

Upvotes: 3

Views: 2197

Answers (2)

Michael Stum
Michael Stum

Reputation: 180934

You can use the Async support in MVC 4 (or an AsyncController if you're on MVC 3)

public async Task<ActionResult> GizmosAsync()
{
    var gizmoService = new GizmoService();
    return View("Gizmos", await gizmoService.GetGizmosAsync());
}

The method in await can then use the time it needs, including Thread.Sleep.

That way, you're not blocking ASP.net from handling other requests.

Upvotes: 4

Eli Algranti
Eli Algranti

Reputation: 9007

You can use a custom ActionFilters.

  • Record the time the request arrived in the OnActionExecuting method.
  • Then on the OnResultExecuted method inspect the result. If it is a valid response let it through, if it is a not authorized response delay it using Thread.Sleep with the desired delay based on the start time recorded.

Just make sure your filter runs before the authorization filter ([Authorize] ?) or is registered before it if you're using global filters and not attributes.

In this way the delay has no impact on authorized users which I assume is the reason you don't want to use Thread.Sleep. Note that Thread.Sleep by default is not very accurate (on the order of 20ms), but network latency to the client should obscure that.

Upvotes: 3

Related Questions