Dispatched Aspect on static method

avistokar's Avatar


19 Oct, 2017 08:13 PM

I tried applying the Dispatched Attribute to a static method but am unable to as it looks like this use case is not supported. Why is it not supported and will it be supported in the future?

  1. Support Staff 1 Posted by PostSharp Techn... on 20 Oct, 2017 09:40 AM

    PostSharp Technologies's Avatar


    The idea behind the DispatchedAttribute aspect is to dispatch the target method to the thread on which the current instance of the object has been created. When a new instance is created, the aspect detects the SynchronizationContext for the current thread and then uses it to dispatch the method execution. For example, UI controls in WPF application are created on the UI thread and so methods marked as [Dispatched] will execute on the UI thread.

    With a static method there's no way to detect where the execution should be dispatched as the method is not associated with any instance. You would need to provide the dispatcher manually anyway, which defeats the purpose of the aspect.


  2. 2 Posted by avistokar on 20 Oct, 2017 10:38 AM

    avistokar's Avatar

    Thanks for the explanation.

    In my WPF app I have help methods that manipulate data bound to UI elements which cause threading problems unless I ensure that the method is executed on the UI thread.

    Simply Invoking the method on the Dispatcher is not a great solution as there is no Dispatcher when inside a test runner. These leads me boiler plate code to detect if I am in a test runner and then to check if the current thread is the UI thread before marhsalling to the UI.

  3. Support Staff 3 Posted by PostSharp Techn... on 20 Oct, 2017 11:07 AM

    PostSharp Technologies's Avatar

    Maybe it will help to turn helper methods into instance methods of a singleton class and then make sure that the singleton instance is created on application startup on UI thread. That should allow you to use the DispatchedAttribute with the helper methods. You can also implement the PostSharp.Patterns.Threading.IDispatcherObject interface on your singleton class to manually control how the methods are dispatched.


  4. Support Staff 4 Posted by PostSharp Techn... on 06 Nov, 2017 02:35 PM

    PostSharp Technologies's Avatar


    We are going to close this request as there have not been any further updates. Please feel free to reopen the discussion if you need more help.

    PostSharp Team

  5. PostSharp Technologies closed this discussion on 06 Nov, 2017 02:35 PM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts


? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac