Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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?

like image 598
Michael J. Gray Avatar asked Dec 06 '25 04:12

Michael J. Gray


1 Answers

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.

like image 193
Michael Stum Avatar answered Dec 07 '25 17:12

Michael Stum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!