Skip to content

Instantly share code, notes, and snippets.

@pnewhook
Last active October 11, 2022 23:02
Show Gist options
  • Save pnewhook/2228bd340a869887ab93 to your computer and use it in GitHub Desktop.
Save pnewhook/2228bd340a869887ab93 to your computer and use it in GitHub Desktop.
HostingEnvironment.QueueBackgroundWorkItem
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