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


RT @seanmckmsft: We now have a feedback forum for #AzureKubernetesService at https://t.co/0isxSTIwhc. Please use this for feature requests…

July 21, 2018 07:20

Azure Container Registry Build Supports All Windows Versions (Preview of Preview) https://t.co/OCkqVP4S9v

July 19, 2018 09:53

How #Microsoft has evolved under Satya Nadella https://t.co/b2e9B6wWu0

July 19, 2018 09:33

@serbrech you've made my day! :)

July 16, 2018 07:07

RT @brendandburns: The @kubernetesio extension for @code now supports creating/integrating minikube clusters from the editor! (and a prett…

July 11, 2018 21:12

Un début de journée normal avec @SFR! @SFR_SAV je vous ai déjà contacté en privé. J'attends un remboursement pour l… https://t.co/6TxfWSJyzJ

July 11, 2018 05:22

@benjguin Moi je tourne à la bière belge ;-)

July 10, 2018 19:25

Introducing Dev Spaces for @Azure #Kubernetes Service https://t.co/nleSg9UrW0

July 10, 2018 10:16

RT @AbelSquidHead: Did you know you can create public projects in #VSTS now? Cool stuff!! https://t.co/IhdCfmNVEx

July 07, 2018 12:19

@SFR_SAV Vous ne pourrez rien me dire de plus que le service téléphonique, autant continuer en public que les gens… https://t.co/UxGr9SVVkW

July 06, 2018 17:28

@philippep92 @petitpatapouf @SFR_SAV @Laurent_MAILLOT @LafibreOrange Preneur ici aussi #Orange, on a voté l'autoris… https://t.co/6DmO566rR5

July 06, 2018 17:25

@philippep92 @petitpatapouf @SFR_SAV @Laurent_MAILLOT Idem dans le 94 à Gentilly. Le service client @SFR_SAV m'a di… https://t.co/eBF3N4H8PH

July 06, 2018 17:11

.@60millions @UFCquechoisir @Arcep est-ce qu'il y a des actions en cours pour régler les problèmes de qualité #SFRhttps://t.co/ZAsoN6POo6

July 06, 2018 16:54

A tous les gens qui ont des soucis avec #SFR, appelez le service client (@SFR / 1023), ils sont obligés de vous déd… https://t.co/1hkWgjjklV

July 06, 2018 16:51

Encore une panne générale de #SFR... Réponse de @SFR_SAV au téléphone: "on est en train de migrer nos clients ADSL… https://t.co/kQaE9pcC7T

July 06, 2018 16:49