Open sandboxFocus

Class BackgroundAttribute

Custom attribute that, when applied on a method, causes the method to execute in the background. This aspect can be applied to a method with void or Task return type.

Namespace: PostSharp.Patterns.Threading
Assembly: PostSharp.Patterns.Threading.dll
Syntax
[MethodInterceptionAspectConfiguration(SerializerType = typeof(MsilAspectSerializer))]
[ProvideAspectRole("Threading")]
[AspectRoleDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, "Tracing")]
[AspectRoleDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, "Caching")]
[AspectRoleDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, "CacheInvalidation")]
[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, typeof(ThreadAwareAttribute))]
[Metric("UsedFeatures", "PostSharp.Patterns.Threading.BackgroundMethod")]
[LinesOfCodeAvoided(1)]
[AspectDescription("Executes the method asynchronously in the thread pool")]
public sealed class BackgroundAttribute : MethodInterceptionAspect, IMethodLevelAspectBuildSemantics, IAspectBuildSemantics, IValidableAnnotation, IAsyncMethodInterceptionAspect, IMethodInterceptionAspect, IMethodLevelAspect, IAspect
Remarks

When this aspect is applied to a method returning a Task, the aspects wraps the method call by a call to Task.Factory.StartNew, therefore executing the whole method in a background thread. Without this aspect, the target method would execute asynchronously, but in the current context, instead of in the background context.

If the IsLongRunning property is set to true, the method will be executed in a new thread. Otherwise, it will be queued into the ThreadPool.

If the target method results in an exception, the exception can be handled by subscribing to the UnhandledException event. Unhandled exceptions are rethrown, typically causing the application to crash.

Constructors

Name Description
BackgroundAttribute()

Initializes a new BackgroundAttribute.

Properties

Name Description
IsLongRunning

Specifies that the method is long-running and should be executed on its own thread, if that is supported on the target platform. If false, the method will be executed in the thread pool.

Methods

Name Description
CompileTimeValidate(MethodBase)

Method invoked at build time to ensure that the aspect has been applied to the right target.

OnInvoke(MethodInterceptionArgs)

Method invoked instead of the method to which the aspect has been applied.

OnInvokeAsync(MethodInterceptionArgs)

Method invoked instead of the method to which the aspect has been applied.