![](/img/trans.png)
[英]Conversion of synchronous methods with Action/Func parameters to asynchronous
[英]Action T synchronous and asynchronous
我有一個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);
這是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);
}
最簡單的選擇:
// 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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.