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 @FredericWickert: Microsoft and #AI for #developers https://t.co/AsivUypQ1v

June 23, 2017 20:37

RT @VaheMicrosoft: Les services Cloud Microsoft localisés ds des datacenters à Paris et Marseille plébiscités par l’écosystème français htt…

June 23, 2017 17:56

#Java: Manage Azure #ContainerService, #CosmosDB, Active Directory #Graph and more https://t.co/C8Qv0rASTl

June 23, 2017 06:49

RT @pierlag: Vous avez aimé #experiences? Ne manquez pas #experiences17, 3&4 octobre 2017 au Palais des Congrès! Inscriptions https://t.co

June 23, 2017 06:10

RT @gabrtv: .NET Core support added to #Draft care of the good folks @cloudbaseit 👏https://t.co/LjUSp0uXMi

June 22, 2017 20:17

Inside Microsoft's #AI Comeback https://t.co/dMJldLxrRy

June 22, 2017 20:04

#DevOps w/ #Containers: CI/CD of Containers from #VisualStudio to #ServiceFabric https://t.co/2VJh9o5Hqh

June 22, 2017 11:54

How Microsoft Is Shifting Focus to Open Source https://t.co/PMONdSbHJn

June 22, 2017 09:37

#DevOps w/ #Containers: Mesosphere DCOS, Azure, Docker, VMware and everything between – Architecture and CI/CD Flow… https://t.co/w0FCPUjs7P

June 22, 2017 08:21

#GDPR Questions? #Azure has answers. https://t.co/3xlQ8WSKyQ

June 22, 2017 07:01

Enable client side monitoring in #Azure with #ApplicationInsights https://t.co/sLcoQG51JS

June 22, 2017 06:43

ASOS: How they migrated from local monolith to #microservices in #Azure https://t.co/cxZxwgtm4g

June 22, 2017 06:36

Modernizing Traditional Applications with @Docker on #WindowsServer and @Azure https://t.co/IK9eYhWmuz

June 21, 2017 09:36

Hackons l’intelligence artificielle à Microsoft experiences’17 https://t.co/a77Ni5Ne0M

June 21, 2017 07:53