Last active
October 11, 2022 23:02
-
-
Save pnewhook/2228bd340a869887ab93 to your computer and use it in GitHub Desktop.
HostingEnvironment.QueueBackgroundWorkItem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Web.Hosting; | |
using System.Web.Mvc; | |
namespace QueueBackgroundWorkItem.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
// notice that the action did need to be declared async | |
public ActionResult Index() | |
{ | |
Func<CancellationToken, Task> workItem = DelayWrite; | |
HostingEnvironment.QueueBackgroundWorkItem(workItem); | |
// the view is returned before the work item is complete | |
return View(); | |
} | |
// Background work items should use async/await to avoid tying up IIS threads | |
// the runtime will provide the cancellation token | |
private async Task DelayWrite(CancellationToken cancellationToken) | |
{ | |
// perform a long running operation, e.g. network service call, computation, file IO | |
await Task.Delay(5000); | |
Trace.WriteLine("Executed from a background work item"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment