我有一个ContextMenuStrip控件,允许您执行一个动作是两种不同的风格:同步和异步.
我试图用泛型覆盖所有内容所以我这样做:
public class BaseContextMenu<T> : IContextMenu { private T executor; public void Exec(Action<T> action) { action.Invoke(this.executor); } public void ExecAsync(Action<T> asyncAction) { // ... }
我如何编写异步方法以执行通用操作并同时使用菜单“执行某些操作”?
我看到BeginInvoke的签名是这样的:
asyncAction.BeginInvoke(this.executor,IAsyncCallback,object);
解决方法@H_403_13@
这是Jeffrey Richter关于.NET异步编程模型的文章.
http://msdn.microsoft.com/en-us/magazine/cc163467.aspx
以下是如何使用BeginInvoke的示例:
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);
}
}
这是一个可以传递给ExecAsync的回调方法:
private void Callback(IAsyncResult asyncResult)
{
Action<T> asyncAction = (Action<T>) asyncResult.AsyncState;
asyncAction.EndInvoke(asyncResult);
}
以下是如何使用BeginInvoke的示例:
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); } }
这是一个可以传递给ExecAsync的回调方法:
private void Callback(IAsyncResult asyncResult) { Action<T> asyncAction = (Action<T>) asyncResult.AsyncState; asyncAction.EndInvoke(asyncResult); }