How to use WPF Dispatcher.BeginInvoke Method

In .NET 2.0 and Windows Forms, you can invoke an asynchronous call to a method with no arguments using code like:

myControl.BeginInvoke(new MethodInvoker(AnotherMethod));

In .NET 3.0 and WPF, the equivalent code would be:

myControl.Dispatcher.BeginInvoke(new Action(AnotherMethod), null);

One place asynchronous calls are useful is in event handlers. In an event handler, you can make an asynchronous call to initiate actions that take place after all event listeners have completed their work. There are many situations where being able to perform an asynchronous call allows you to do things with minimal additional coding.

One example of the usefulness of asynchronous calls can be seen with Essential Grid. GridControl exposes an event, CurrentCellStartEditing, that allows you to catch the action of the current cell starting to edit. You may want to catch this action so you can position the cursor at a certain position in the text. But, when you try to implement this behavior in the event handler, the GridControl code that raises CurrentCellStartEditing later resets the cursor position according to the property setting. This subsequent action undoes your work of specifically setting the cursor position. One way around this problem is to initiate an asynchronous call to a method that positions the cursor on the current cell where you want it to be. In this manner, your positioning code is executed after the grid’s CurrentCellStartEditing code has completed, allowing your cursor position to take precedence over the position set by the GridControl.

clayb