I have a ContextMenuStrip control that allows you to execute an action is two different flavors: Sync
and Async
.
I am trying to cover everything using Generics so I did this:
public class BaseContextMenu<T> : IContextMenu
{
private T executor;
public void Exec(Action<T> action)
{
action.Invoke(this.executor);
}
public void ExecAsync(Action<T> asyncAction)
{
// ...
}
How I can write the async method in order to execute the generic action and 'do something' with the menu in the meanwhile?
I saw that the signature of BeginInvoke
is something like:
asyncAction.BeginInvoke(this.executor, IAsyncCallback, object);
Here is Jeffrey Richter's article on .NET asynchronous programming model. http://msdn.microsoft.com/en-us/magazine/cc163467.aspx
Here is an example of how BeginInvoke can be used:
public class BaseContextMenu<T> : IContextMenu
{
private T executor;
public void Exec(Action<T> action)
{
action.Invoke(this.executor);
}
public void ExecAsync(Action<T> asyncAction, AsyncCallback callback)
{
asyncAction.BeginInvoke(this.executor, callback, asyncAction);
}
}
And here is a callback method that can be passed to the ExecAsync:
private void Callback(IAsyncResult asyncResult)
{
Action<T> asyncAction = (Action<T>) asyncResult.AsyncState;
asyncAction.EndInvoke(asyncResult);
}
Simplest option:
// need this for the AsyncResult class below
using System.Runtime.Remoting.Messaging;
public class BaseContextMenu<T> : IContextMenu
{
private T executor;
public void Exec(Action<T> action) {
action.Invoke(this.executor);
}
public void ExecAsync(Action<T> asyncAction) {
// specify what method to call when asyncAction completes
asyncAction.BeginInvoke(this.executor, ExecAsyncCallback, null);
}
// this method gets called at the end of the asynchronous action
private void ExecAsyncCallback(IAsyncResult result) {
var asyncResult = result as AsyncResult;
if (asyncResult != null) {
var d = asyncResult.AsyncDelegate as Action<T>;
if (d != null)
// all calls to BeginInvoke must be matched with calls to
// EndInvoke according to the MSDN documentation
d.EndInvoke(result);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With