| Severity | Error |
| Reported by | PostSharp.Patterns.Threading |
| Message | Method <Method> cannot be enhanced with the [Dispatched] aspect because it is a static method. |
Cause
The DispatchedAttribute aspect executes a method in the thread of the object, typically the UI thread. The aspect takes the dispatcher of the object: the object implements IDispatcherObject, as UI controls do, or captures the synchronization context of the thread that creates it. A static method has no object, so the aspect cannot know in which thread to execute it.
PostSharp reports THR023 when the aspect is applied to a static method, in any execution mode.
In the following example, the ShowMessage method is static.
using System;
using System.Threading;
using PostSharp.Patterns.Threading;
namespace Errors.THR023_Error;
public class StatusBar
{
// A static method has no object whose thread it could run in.
[Dispatched]
public static void ShowMessage( string message )
{
Console.WriteLine( $"Status: {message}" );
}
}
public static class Program
{
public static void Main()
{
// A console application has no UI thread, so the status bar uses the synchronization context of the main thread.
SynchronizationContext.SetSynchronizationContext( new SynchronizationContext() );
StatusBar.ShowMessage( "Ready" );
}
}
error THR023: THR023_Error.cs(11,24): Method Errors.THR023_Error.StatusBar.ShowMessage(System.String) cannot be enhanced with the [Dispatched] aspect because it is a static method.
Resolution
- Make the method an instance method of the object that belongs to the UI, such as a view or a control, and call it on an instance.
- When the method must remain static, remove the aspect and dispatch the call yourself, for example with the
PostorSendmethod of theSynchronizationContextof the UI thread.
In the following example, ShowMessage is an instance method.
using System;
using System.Threading;
using PostSharp.Patterns.Threading;
namespace Errors.THR023_Fixed;
public class StatusBar
{
// An instance method runs in the thread of the object that was captured when the object was created.
[Dispatched]
public void ShowMessage( string message )
{
Console.WriteLine( $"Status: {message}" );
}
}
public static class Program
{
public static void Main()
{
// A console application has no UI thread, so the status bar uses the synchronization context of the main thread.
SynchronizationContext.SetSynchronizationContext( new SynchronizationContext() );
var statusBar = new StatusBar();
statusBar.ShowMessage( "Ready" );
}
}
Status: Ready
See Also
Reference
Other Resources