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


How Microsoft’s Brendan Burns is trying to make cloud-native app deployment as easy as coding https://t.co/kPa2mzqE9V

December 18, 2017 07:44

RT @brendandburns: Really great overview of @Azure container service! https://t.co/7fk42Ud7m5

December 14, 2017 17:40

#KubeCon 2017 Demo - Istio and Brigade CI/CD https://t.co/60uaK82fIJ

December 14, 2017 08:18

Azure #Functions CI/CD pipeline for #Nodejs using #VSTS https://t.co/3UElDsDsDL

December 14, 2017 08:13

AKS cluster upgrades and managed #Kubernetes in #Azure https://t.co/b0naeEUwl1

December 12, 2017 16:01

Microsoft Azure <3 France ! https://t.co/w4Ak8f4QWN

December 12, 2017 08:09

The future is here! The #Quantum Development Kit has been released :) https://t.co/8mSieAEbCr

December 12, 2017 07:16

A tour of #containerd 1.0 https://t.co/27jtxIu17d

December 12, 2017 07:10

Last week in Azure: OSBA, DevOps and Kubernetes, VM sizes, and more https://t.co/vq6jtWLYTq

December 12, 2017 07:08

RT @BradSmi: We believe #AI is a game changer in creating solutions to protect the planet. That’s why we’re expanding #AIforEarth. #OnePlan

December 11, 2017 13:52

WSL Interoperability with #Docker https://t.co/xtiUafCPyq

December 11, 2017 11:58

RT @jpetazzo: If you are using @docker (or are planning to) to help you in your DevOps initiatives, you might want to read this: https://t.…

December 09, 2017 12:20

RT @benjguin: Free eBook – The Developer’s Guide to Microsoft Azure now available https://t.co/z9VeGYRDQy https://t.co/V0ozQPJllh

December 08, 2017 08:08

Check out the new #Azure Application Architecture Guide https://t.co/M3wIQfkRhi

December 08, 2017 07:53

What’s brewing in Visual Studio Team Services: December 2017 Digest https://t.co/jL8yNATyJR

December 08, 2017 07:51