I am attempting to write an extension method which will simplify cross-thread event handling. The below is what I have conceived and by my understanding it should work; however I am getting a cross-thread exception when the EndInvoke method is called...
using System;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace SCV {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
private static event EventHandler _Test;
public static event EventHandler Test {
add { MainWindow._Test += value; }
remove{ MainWindow._Test -= value; }
}
private static async Task OnTest( ) {
if ( MainWindow._Test != null )
await MainWindow._Test.ExecuteAsync( null, EventArgs.Empty );
}
private LinearGradientBrush brshSomeBrush = new LinearGradientBrush(Colors.Red, Colors.Black, new Point(0, 0), new Point(1, 1));
public MainWindow( ) {
InitializeComponent( );
MainWindow.Test += ( S, E ) => this.Background = this.brshSomeBrush;
this.Loaded += async ( S, E ) => await MainWindow.OnTest( );
}
}
static class Extensions {
public static async Task ExecuteAsync( this EventHandler eH, object sender, EventArgs e ) {
await Task.WhenAll( eH.GetInvocationList( ).Cast<EventHandler>( ).Select( evnt => Task.Run( ( ) => {
System.Windows.Controls.Control wpfControl;
System.Windows.Forms.Control formControl;
Action begin = ( ) => evnt.BeginInvoke( sender, e, IAR => ( ( IAR as AsyncResult ).AsyncDelegate as EventHandler ).EndInvoke( IAR ), null );
if ( evnt.Target is System.Windows.Controls.Control && !( wpfControl = evnt.Target as System.Windows.Controls.Control ).Dispatcher.CheckAccess( ) )
wpfControl.Dispatcher.Invoke( begin );
else if ( evnt.Target is System.Windows.Forms.Control && ( formControl = evnt.Target as System.Windows.Forms.Control ).InvokeRequired )
formControl.Invoke( begin );
else
begin( );
} ) ) );
}
}
}
What would be the reason for this to still throw an exception? How am I doing this wrong?
You're calling the delegate on the right thread - but the delegate itself then calls evnt.BeginInvoke
, which executes the evnt
delegate on the thread pool... so you still end up executing the real underlying delegate (in this case _Test
, will set the background colour) on a non-UI thread.
You've already marshaled to the right thread on which to execute the delegate - so just execute it with evnt(sender, e)
.
See more on this question at Stackoverflow