Reputation: 9896
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
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
Reputation: 9007
You can use a custom ActionFilters.
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