In the ASP. NET Web API project, use Hangfire to process Background tasks.

Source: Internet
Author: User
Tags msmq

In the ASP. NET Web API project, use Hangfire to process Background tasks.

The current project has the following requirement: a front-end user's operation needs to trigger message push to different devices. Because of the specific push function, we use third-party services. However, this service call may be delayed sometimes. Therefore, we want to Implement Asynchronous execution of message push and user frontend operations, that is, to automatically execute messages in the background without blocking the operations of front-end users, in addition, it is best to implement failure retry and other functions.

After some research and comparison, we found that using the Hangfire component can better meet this requirement. In order to give you a demonstration, I simplified the code here and made a sample program.

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

 

Step 1: Create an ASP. NET Web API Project

 

Step 2: install the necessary nuget package

Open Nuget Package Manager Console

First install the Hangfire component (Core, MemoryStorage). Note that because the latter depends on the former, you only need to run the following command.

Install-Package Hangfire. MemoryStorage

Storage means Storage. The background tasks of Hangfire need to be saved in one place. It supports SQL Server Storage and MemoryStorage by default. Using MemoryStorage is undoubtedly the simplest (without any external dependencies ). Of course, the biggest problem is that it is stored in the memory. If the website restarts due to a problem, the unexecuted tasks will disappear.

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

 

Next, enable Owin for the current project. About what is OWin, I am not prepared here to do more instructions, interested students can refer to: http://www.cnblogs.com/dudu/p/what-is-owin.html and http://owin.org/There are http://www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana

Install-Package Microsoft. Owin. Host. SystemWeb

 

Step 3: Add Owin Startup Class

Modify Startup. cs to the following code:

Using Hangfire; using Hangfire. memoryStorage; using Microsoft. owin; using Owin; [assembly: OwinStartup (typeof (WebApplicationWebApiHangfireSample. startup)] namespace WebApplicationWebApiHangfireSample {// <summary> // demonstrate the Hangfire configuration /// Author: chen xizhang // </summary> public class Startup {public void Configuration (IAppBuilder app) {// For more information on how to configure your application, visit http: // go. Microsoft.com/fwlink /? LinkID = 316888 // specify the Hangfire memory to store the background task information GlobalConfiguration. configuration. useMemoryStorage (); // enable the middleware HangfireServer (which will be automatically released) app. useHangfireServer (); // enable the Hangfire dashboard (you can see the status and progress of the task) app. useHangfireDashboard ();}}}

 

 

Step 4: implement a simple Web API to start background tasks

Using Hangfire; using System. diagnostics; using System. web. http; namespace WebApplicationWebApiHangfireSample. controllers {/// <summary> /// API used to be made public to the front-end user. /// Author: Chen xizhang /// </summary> public class MessageController: apiController {// <summary> // This is the static method used to send messages. // </summary> /// <param name = "message"> </param> public static void Send (string message) {EventLog. writeEntry ("EventSystem", string. format ("this is the message sent by the Hangfire background task: {0}, time: {1}", message, DateTime. now);} public IHttpActionResult Post (string content) {// here you can do some business judgment or operations // when you need to push, call the following method to BackgroundJob. enqueue () => Send (content); // returns the final result (return immediately, not blocked) return OK ();}}}

 

Step 5: perform a test

I use Fiddler to simulate client calls

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

Soon you will see the task status in the Dashboard (with 1000 tasks)

But soon (less than 1 second), all these tasks are processed.

 

We can see the message in the Windows Event Log

The above is my simple demo. Of course, if you want to implement failed retry or more interesting features (such as scheduled sending), you can continue to refer to the official documentation.

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

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.