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


Investing deeply in #Terraform on #Azure https://t.co/FkI5tIdCSM

August 18, 2017 09:27

Azure Service Bus .NET Standard Client Generally Available #dotnet https://t.co/OApdNciezA

August 18, 2017 09:25

If you are using @Azure #ContainerRegistry the team is looking for feedbacks: https://t.co/3worKrTubj cc @SteveLasker #Docker #Container

August 18, 2017 06:51

RT @nirmsk: Azure App Service Linux customer sotry: https://t.co/lNhu6Pq0OI "Using App Service on Linux instead of infrastructure services"

August 18, 2017 06:32

What is containerd ? https://t.co/nL6u5mVozD

August 17, 2017 12:21

New release of #Docker Enterprise Edition w/ both #Windows & #Linux containers support! #DockerEE https://t.co/N9e81qQgGj

August 17, 2017 11:44

#CloudCoverShow Episode 233: #Azure Event Grid with Bahram Banisadr https://t.co/2JNJ0eZdI6

August 17, 2017 11:35

#CloudCoverShow Episode 232: #Azure #Container Instances https://t.co/Opu3y1j8aD

August 17, 2017 11:11

Announcing #aspnet Core 2.0 #dotnetcore https://t.co/vNRZpGgAv8

August 17, 2017 11:06

#Microservices and #Docker containers: Architecture, Patterns and Development guidance https://t.co/wQN5KeAHqT

August 17, 2017 11:05

#Maven: Deploy #Java Web Apps to #Azure https://t.co/GFT4IDVssV

August 17, 2017 08:17

Announcing deploy to #Azure app service #Jenkins plugin and more https://t.co/CitUtOPmDp

August 17, 2017 08:15

Microsoft’s Lightweight Linux Runtime Environment Comes to Windows Server https://t.co/0k56clGMhK

August 17, 2017 07:50

With Event Grid, #Microsoft Provides the Missing Half of #Azure #Serverless Computing https://t.co/FoRuMpAZ8M

August 17, 2017 07:48

#Kubernetes Connector for #Azure Container Instances! https://t.co/SY7QwjnrlV

August 17, 2017 07:40