• Stars
    star
    109
  • Rank 319,077 (Top 7 %)
  • Language
    C#
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A component that registers "fire and forget" tasks with the ASP.NET runtime.

logo

Important Note

The .NET framework 4.5.2 introduced HostingEnvironment.QueueBackgroundWorkItem, which is very similar to this library. Consider upgrading to 4.5.2 and using HostingEnvironment.QueueBackgroundWorkItem instead of the BackgroundTaskManager.Run provided by this library.

Fire and Forget

This is one solution for a "fire and forget" scenario on ASP.NET: when you have enough data to send the response, but you still have additional work to do.

You want to return the response right away, but you also need to start the additional work in the background.

Important: "fire and forget" on ASP.NET is dangerous! Please read the discussion below to understand why!

How to Use

Download and install the Nito.AspNetBackgroundTasks NuGet package.

You can start background work by calling BackgroundTaskManager.Run:

BackgroundTaskManager.Run(() =>
{
  MyWork();
});

Run also understands asynchronous methods:

BackgroundTaskManager.Run(async () =>
{
  await MyWorkAsync();
});

If your background work is long-running or asynchronous, then use the BackgroundTaskManager.Shutdown cancellation token. This token is set when the ASP.NET runtime asks to shut down the application.

BackgroundTaskManager.Run(async () =>
{
  await MyWorkAsync(BackgroundTaskManager.Shutdown);
});

Finally, note that all exceptions are ignored. If you want to log exceptions, you'll have to do it yourself:

BackgroundTaskManager.Run(() =>
{
  try
  {
    MyWork();
  }
  catch (Exception ex)
  {
    Log(ex);
  }
});

The Problem with Fire and Forget

ASP.NET lives around a request lifecycle. If there are no active requests, ASP.NET may decide to unload your application. This is perfectly normal; by default IIS will recycle your application every so often just to keep things clean.

This causes a problem for "fire and forget": ASP.NET isn't even aware that the background work is running. BackgroundTaskManager will register the background work with the ASP.NET runtime so it is aware of it. However, it's still not a perfectly reliable solution.

The Reliable Solution

The reliable way to handle this is complicated:

  • Add the background work to a reliable queue, such as an Azure queue or MSMQ.
  • Have an independent worker process that executes the work in the queue, such as an Azure WebJob, an Azure Worker Role, or a Win32 Service.
  • Determine some means to notify the end-user that the background processing has completed, such as email or SignalR.

One good, reliable solution is HangFire.

The Unreliable Solution

This solution is simpler, but dangerous: push the background work off to another thread within the ASP.NET process.

This solution is dangerous because it is not reliable; there is no guarantee that the background work will ever be done.

If your system needs the background work to be done, then you must use the proper, reliable solution above. There is no other way.

However, if you are perfectly OK with occasionally losing background work without a trace, then you can use the dangerous solution. For example, you have an on-disk cache that you want to update, but you don't want to slow down the requests. You want to send the response immediately and then update the on-disk cache in the background.

To reiterate: "fire and forget" on ASP.NET actually means "I don't care whether this work actually gets done or not".

Minimizing Unreliability

Just because the solution is unreliable, doesn't mean it must be totally unreliable.

AspNetBackgroundTasks is a NuGet package that allows you to register "fire and forget" work with the ASP.NET runtime. The unreliability is minimized; the danger is mitigated. It is still unreliable and dangerous, however.

Futher Reading

Phil Haack: "The Dangers of Implementing Recurring Background Tasks in ASP.NET"

Stephen Cleary: "Returning Early from ASP.NET Requests"

More Repositories

1

AsyncEx

A helper library for async/await.
C#
3,295
star
2

Comparers

The last comparison library you'll ever need!
C#
400
star
3

StructuredConcurrency

Structured concurrency support for C#
C#
203
star
4

Mvvm

MVVM helpers, including calculated properties and asynchronous notification tasks.
C#
132
star
5

Deque

Double-ended queue
C#
105
star
6

Disposables

IDisposable helper types.
C#
98
star
7

CalculatedProperties

Easy-to-use calculated properties for MVVM apps
C#
73
star
8

AsyncDiagnostics

Easy-to-use exception causality chains for async/await.
C#
61
star
9

BrowserBoss

Easily script browsers.
C#
55
star
10

Try

The Try monad (Error/Exceptional monad) for C#
C#
44
star
11

ConnectedProperties

Dynamically attach properties to (almost) any object instance.
C#
41
star
12

Guids

Helper types for creating and interpreting GUIDs.
C#
27
star
13

Presentations

Repository for presentations
C#
27
star
14

PegLeg

A PEG parser for C#, using code generators
C#
22
star
15

CrossDomainSingleton

An AppDomain-aware, thread-safe singleton that ensures only one instance exists in the entire application.
C#
22
star
16

LocalTelemetry

Local dashboards for telemetry collection.
18
star
17

Docs

Documentation of various and sundry matters
16
star
18

grounded-chatgpt

ChatGPT, but grounded in custom data
C#
16
star
19

HashAlgorithms

CRC calculation for .NET
C#
16
star
20

DependencyInjection

Helpers for Microsoft.Extensions.DependencyInjection.
C#
15
star
21

ArraySegments

A library for slicing and dicing arrays (without copying).
C#
13
star
22

Scripts

Misc single-file scripts and utilities
C#
13
star
23

ArcDb

An ACID .NET relational database
12
star
24

Mvvm.CalculatedProperties

Automatically raise PropertyChanged in MVVM applications.
C#
11
star
25

Cancellation

Types to assist with cancellation handling.
C#
11
star
26

DisplayProfiles

An application that saves and restores display monitor layouts.
C#
10
star
27

Mvvm.Core

Basic MVVM helpers.
C#
10
star
28

AsyncCTPUtil

Utility code originally distributed as part of the Async CTP
C#
10
star
29

ProjProps

A dotnet tool that displays project properties.
C#
10
star
30

Logging

Library for using scopes with Microsoft.Extensions.Logging.
C#
10
star
31

AsyncEx.Testing

Helper types for writing unit tests for asynchronous code.
C#
9
star
32

ProducerConsumerStream

A producer/consumer collection of bytes with a Stream-based API.
C#
8
star
33

OptionParsing

Flexible command-line parsing library
C#
8
star
34

BuildTools

Miscellaneous tools for building .NET Core libraries.
7
star
35

UniformResourceIdentifiers

Standard-compliant URI encoders and parsers
C#
6
star
36

iterjs

ES6 library for working with iterables and iterators
JavaScript
5
star
37

Quicly

An implementation of IETF QUIC in .NET
C#
4
star
38

StrongNamer

Simple app that strong-names NuGet packages.
C#
3
star
39

AsyncUnitTests

Helpers for async unit testing.
C#
3
star
40

blog-stephencleary-dotcom

blog.stephencleary.com
HTML
2
star
41

Hosting

.NET Generic Host for UI applications
C#
2
star
42

Collections.Async

Async-compatible producer/consumer collections.
2
star
43

comments.stephencleary.com

Comments for stephencleary.com.
JavaScript
2
star
44

stephencleary-dotcom

HTML
1
star
45

LoggerProviderHelpers

Helper types for implementing Microsoft's ILoggerProvider.
1
star
46

ARC

A simple dynamic language. Like JavaScript, but better!
C#
1
star
47

DockerLifetime

A .NET Core lifetime service for Docker containers
1
star
48

glob

GitHub Action that finds files using globs (wildcards)
JavaScript
1
star
49

Presentations-IntermediateAsync

Sample code for presentation given at GRDevDay 2013-03-02
1
star
50

Hymnals

Public domain hymnals
LilyPond
1
star