Dispatching a Method to Background

Long running processes will block the further execution of code while the system waits for them to complete. When you are building applications it's common to push long running processes to the background so that other processes can continue without waiting. Two common ways of doing this are with asyncronous processing and the BackgroundWorker. Both require a lot of boiler plate code to push execution to another thread.

PostSharp provides you with the ability to push execution of a method to a background thread without having to worry about all of the boiler plate code.

To add [Background] attribute:

  1. Find the method that you want to push to the background for execution.

    C#
    public class CustomerRepository 
    { 
        public void DoStuff() 
        { 
            Console.WriteLine("Things are getting done"); 
        } 
    }
  2. Select "Execute method in the background" from the Smart Tag available under the method name.

    Background 1
  3. You'll notice that only one change was made to your codebase. The [Background] attribute was added to the class you were targeting. Now when this method executes in your application it will occur in another thread and will allow for the calling code to continue executing.

    C#
    public class CustomerRepository 
    { 
        [Background] 
        public void DoStuff() 
        { 
            Console.WriteLine("Things are getting done"); 
        } 
    }

Those simple steps are all that is required for you to declare that a method should be executed in a background thread.

See Also