Using Hangfire to implement background task processing in an ASP. NET Web API Project

Source: Internet
Author: User
Tags msmq

There is a requirement in the current project: an action by a front-end user that triggers a message push to a different device. We use third-party services because we push this specific feature. And this service call may sometimes have a delay, for this reason, we want to push the message with the user front-end operation implementation of asynchronous execution, is to automate in the background, do not block the operation of the front-end users, and it is best to implement failure retry and other functions.

After some research comparisons, we find that using the Hangfire component can be a good way to achieve this requirement. In order to give you a demonstration, I have simplified the code here and made an example program.

I am not here to detail the basic usage of hangfire, interested students can refer to the official website http://hangfire.io/and documentation http://docs.hangfire.io/en/latest/

First step: Create an ASP. NET Web API Project

Step Two: Install the necessary NuGet package

Open NuGet Package Manager Console

First install the Hangfire component (Core,memorystorage), note that because the latter is dependent on the former, we only need to run the following command to

Install-package Hangfire.memorystorage

Storage is the meaning of storage, Hangfire background task is to need a place to save, it is supported by default SQL Server storage and memorystorage. The adoption of Memorystorage is undoubtedly the simplest (no external dependencies are required). Of course, the biggest problem is that, because it is in memory, if the site has a problem restart, then the task is not completed will disappear.

If you want to use SQL Server, you can refer to http://docs.hangfire.io/en/latest/configuration/using-sql-server.html and even combine MSMQ to improve availability Http://docs.hangfire.io/en/latest/configuration/using-sql-server-with-msmq.html

Next, enable Owin support for the current project. about what is Owin, I do not want to do more instructions here, interested students can refer to: http://www.cnblogs.com/dudu/p/what-is-owin.html and http://owin.org/also have HTTP// Www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana

Install-package Microsoft.Owin.Host.SystemWeb

Step three: Add Owin Startup Class

Modify Startup.cs to the following code

usingHangfire;usingHangfire.memorystorage;usingMicrosoft.owin;usingOwin; [Assembly:owinstartup (typeof(Webapplicationwebapihangfiresample.startup))]namespacewebapplicationwebapihangfiresample{// <summary>    /// demo Hangfire configuration    // Chen Xizhang    // </summary>     Public classStartup { Public voidConfiguration (Iappbuilder app) {//For more information on what to configure your application, visit http://go.microsoft.com/fwlink/? linkid=316888            //Specify Hangfire use memory to store background task informationGlobalConfiguration.Configuration.UseMemoryStorage ();//Enable Hangfireserver this middleware (it will automatically release)App. Usehangfireserver ();//Enable Hangfire's dashboard (you can see the status of the task, progress and other information)App.        Usehangfiredashboard (); }    }}

Fourth step: Implement a simple web API to start a background task

usingHangfire;usingSystem;usingSystem.Diagnostics;usingSystem.Web.Http;namespacewebapplicationwebapihangfiresample.controllers{// <summary>    /// API used to publicly call the front-end user    // Chen Xizhang    // </summary>     Public classMessagecontroller:apicontroller {// <summary>        /// This is a static method for sending messages        // </summary>        /// <param name= "message" ></param>         Public Static voidSend (stringMessage) {EventLog.WriteEntry ("EventSystem",string. Format ("This is a message sent by the Hangfire background task: {0}, Time: {1}", message, DateTime.Now)); } PublicIhttpactionresult Post (stringContent) {//You can do some business judgment or operation here                        //Then need to push, call the following method toBackgroundjob.enqueue (() = Send (content));//Last return (here is immediate return, will not block)            returnOk (); }    }}

Fifth Step: Test

I use Fiddler to impersonate a client call

We can easily launch a large number of requests, such as the following

See the task status in Dashboard soon (with 1000 tasks)

But soon (less than 1 seconds), these tasks are all done.

We can see the message in the Windows event log

The above is my simple demo example. Of course, if you also want to implement failed retries, or more interesting features, such as timed sends, you can continue to refer to the official documentation.

This sample code can be downloaded here Http://files.cnblogs.com/files/chenxizhang/WebApplicationWebApiHangfireSample.zip

Using Hangfire to implement background task processing in an ASP. NET Web API Project

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.