Open sandboxFocus

Class BackgroundAttribute

Custom attribute that, when applied to 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 aspect wraps the method call in 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.

A build-time error is emitted if the target method has ref or out parameters, or if it is an instance method of a class annotated with ThreadAffineAttribute or ActorAttribute. To execute a method in the UI thread instead, use the DispatchedAttribute aspect.

Constructors

Name Description
BackgroundAttribute()

Initializes a new instance of the BackgroundAttribute class.

Properties

Name Description
IsLongRunning

Gets or sets a value indicating whether 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.

See Also