我有一个ContextMenuStrip控件,允许您执行两种不同的操作:Sync
和Async
。
我试图用泛型来覆盖所有内容,所以我这样做了:
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);
答案 0 :(得分:9)
这是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);
}
答案 1 :(得分:3)
最简单的选择:
// 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);
}
}
}