Processing jobs in a console application¶

To start using Hangfire in a console application, you’ll need to install Hangfire packages to your console application first. So, use your Package Manager Console window to install it:

  1. PM> Install-Package Hangfire.Core

Then, install the needed package for your job storage. For example, you need to execute the following command to use SQL Server:

  1. PM> Install-Package Hangfire.SqlServer

Hangfire.Core package is enough

Please don’t install the Hangfire package for console applications as it is a quick-start package only and contain dependencies you may not need (for example, Microsoft.Owin.Host.SystemWeb).

After installing packages, all you need is to create a new Hangfire Server instance and start it as written in the previous chapter. However, there are some details here:

  • Since the Start method is non-blocking, we insert a Console.ReadKey call to prevent instant shutdown of an application.
  • The call to Stop method is implicit – it is made through the using statement.
  1. using System;
  2. using Hangfire;
  3. using Hangfire.SqlServer;
  4.  
  5. namespace ConsoleApplication2
  6. {
  7. class Program
  8. {
  9. static void Main()
  10. {
  11. GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string");
  12.  
  13. using (var server = new BackgroundJobServer())
  14. {
  15. Console.WriteLine("Hangfire Server started. Press any key to exit...");
  16. Console.ReadKey();
  17. }
  18. }
  19. }
  20. }

原文:

http://docs.hangfire.io/en/latest/background-processing/processing-jobs-in-console-app.html