Run background tasks in aspnet applications with dotnet Framework 4.5.2

May 13, 2014 -

Few days ago Microsoft has announced the availability of the .NET Framework 4.5.2. This new version brings some new features and improvements to ASP.NET. It is now very easy to run some background tasks from an ASP.NET Web app, using the new HostingEnvironment API. It allows to enqueue background tasks (as simple as working with the thread pool) and avoids IIS app pools shutdown until the tracked tasks are completed.

For a complete description of this new .NET Framework version, go to this page. You can find the runtime and developer pack installers here.

Once you’ve installed .NET Framework 4.5.2 and the developer tools, open Visual Studio and create a new web application project that targets the .NET Framework 4.5.2 :


In this post, I have choose to use the HostingEnvironment api to queue thumbnail generation when the user uploads a picture (really simple scenario). The HostingEnvironment class defines a method QueueBackgroundWorkItem that takes an Action<CancellationToken> or a Func<CancellationToken,Task> as parameters.

To generate the thumbnail I have used the System.Drawing API and created the following simple helper :

public class ThumbnailHelper
    public static Task CreateThumbnail(string filePath)
        return Task.Factory.StartNew(() =>
            Image originalImage = Bitmap.FromFile(filePath);

            int thumbWidth, thumbHeight;

            thumbWidth = 250;
            thumbHeight = (originalImage.Height * 250) / originalImage.Width;

            Image thumbnail = originalImage.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero);

            string thumbFileName = string.Format("{0}_thumb{1}", Path.GetFileNameWithoutExtension(filePath), Path.GetExtension(filePath));
            string thumbFilePath = Path.Combine(Path.GetDirectoryName(filePath), thumbFileName);


The cshtml code :

    ViewBag.Title = "Upload a new picture";


@using(Html.BeginForm("Upload", "Picture", FormMethod.Post, new{ enctype = "multipart/form-data"}))
    <div class="form-group">
        <label for="file">Choose a picture</label>
        <input type="file" name="file" id="file" />
    <div class="form-group">
        <input type="submit" value="Upload and create thumbnail" class="btn btn-primary"/>

and the controller code :

public class PictureController : Controller
    public ActionResult Upload()
        return View();

    public ActionResult Upload(HttpPostedFileBase file)
        var appDataPath = Server.MapPath("~/App_Data");
        string filePath = Path.Combine(appDataPath, file.FileName);

        HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
            return ThumbnailHelper.CreateThumbnail(filePath);

        return RedirectToAction("Upload");

As you can see in the code above, just after that the picture is saved in the App_Data folder, a task is queued using the HostingEnvironment api. Now, you can be sure that the app pool of your application will not stop until all the thumbnails are generated.

Hope this helps Winking smile






Announcing general availability of @Azure database services for #MySQL and #PostgreSQL

March 22, 2018 09:59

Running your private #Kubernetes cluster on #Azure with ACS Engine

March 21, 2018 06:34

How to expose your #Kubernetes workloads on @Azure

March 18, 2018 11:22

RT @as_w: .@Azure Container Instances (ACI) across 3 regions in under 30 seconds with Azure Traffic Manager by @as_w

March 17, 2018 09:41

RT @nepeters: Integrate #Azure storage into your #Kubernetes deployments with Open Service Broker for Azure. Give it a spin with this ready…

March 17, 2018 09:40

RT @AzureFunctions: Great stuff from @jeffhollan! Reliable messaging with Functions and Event Hubs.

March 15, 2018 22:22

Bonsoir @SFR @SFR_SAV, pour la 23ème fois depuis le 28 janvier, coupure de la fibre ! Synchro KO. Quand est-ce que…

March 15, 2018 21:10

@nlamirault @KubernetesParis @sferquel L'intérêt est d'avoir un cluster kubernetes local sur le poste de dev, rempl…

March 15, 2018 13:13

@NicoRobPro @Uber Ouais, et puis après il a repris le périph à l'envers, et après il a oublié de tourner à gauche d…

March 15, 2018 07:49

And for those who want to try Service Catalog + Open Service Broker on @Azure with Azure #Container Service (AKS),…

March 15, 2018 07:45

Slides from my talk @KubernetesParis meetup yesterday about #Kubernetes Service Catalog and Open Service Broker for…

March 15, 2018 07:43

@KubernetesParis @sferquel @joinstationf @Docker @kubernetesio Merci ! Mes slides sont dispo ici :

March 15, 2018 07:42

Pourquoi faire simple quand on peut faire compliqué ^^ arrivée en beauté : "wesh faut que j'arrête et que je dorme…

March 14, 2018 23:04

Quand ton chauffeur @Uber sait pas utiliser Waze et transforme un trajet de 10 minutes en 30 minutes en arrêtant pa…

March 14, 2018 22:52

RT @thomasjkerjean: C’est avec fierté que nous @microsoftfrance ouvrons aujourd’hui nos Datacenters à Paris & Marseille! @BJavelot @jblefev

March 14, 2018 22:46