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 :

image

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);

            thumbnail.Save(thumbFilePath);
        });
    }
}

The cshtml code :

@{
    ViewBag.Title = "Upload a new picture";
}

<h2>@ViewBag.Title</h2>

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

and the controller code :

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

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

        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

Julien

Comments

Share

Tags


Twitter


#Kubernetes for Edge Computing: The Microsoft #Azure Approach https://t.co/D6pGrqIBKm

May 25, 2018 05:52

#Azure the cloud for all – highlights from Microsoft BUILD 2018 https://t.co/TH5poYxV0D

May 25, 2018 05:44

RT @satyanadella: @EmmanuelMacron Honored to join the #TechforGood Summit with @EmmanuelMacron. Collectively we have a responsibility to en…

May 23, 2018 15:44

@IOI__655321 @StravaSupport It would be nice if the sync was working all the time and does not take 5+ hours to app… https://t.co/YFOaVCMNRS

May 20, 2018 15:41

RT @brendandburns: More container wisdom from @jessfraz This time in multitenant kubernetes! Really great stuff. https://t.co/Y8xD3qWnVO

May 19, 2018 06:40

RT @Tyriar: VS @code tip: Turn VS Code into a quick notepad with highlighting by adding `"files.defaultLanguage": "markdown"` to your setti…

May 18, 2018 13:45

RT @brendandburns: Great article on how @azure is delivering on the vision of an intelligent edge for IoT via containers, kubernetes and th…

May 17, 2018 06:27

This is really awesome. #SurfaceHub2 https://t.co/HOhrMcRBBp

May 15, 2018 17:05

@benjiiim WOW!

May 15, 2018 17:03

#Azure confidential computing https://t.co/gSuQekTNrb

May 15, 2018 17:03

Azure #Kubernetes Service now has built-in http ingress application routing using #Azure DNS Zone -> https://t.co/tXuAC0cMEa

May 14, 2018 09:01

@lamouetterieuse Ce n'est pas avec docker compose mais il y a une notion de container group avec ACI: https://t.co/G4GLsfjGKP

May 11, 2018 19:57

#Azure SignalR Service, a fully-managed service to add real-time functionality https://t.co/wLiDQveigC

May 11, 2018 17:28

Virtual Network Service Endpoints for Azure #CosmosDB is now generally available https://t.co/ahJT2KnimD

May 11, 2018 16:18

Multi-container on #Azure #Linux Web App, w/ #docker compose and #Kubernetes manifests support! https://t.co/p4tiCPFH67

May 11, 2018 14:40