2010-03-12 26 views
5

Bir eylemi yürütmenize izin veren bir ContextMenuStrip denetimi var, iki farklı tat: Sync ve Async.Eylem T senkronize ve senkronize olmayan

bunu benim yaptığımı bu yüzden Genellemelere kullanarak her şeyi kapsayacak şekilde çalışıyorum:

Ben jenerik eylemi yürütmek ve bu arada menü ile 'bir şeyler' için zaman uyumsuz yöntemini yazabilirsiniz nasıl
public class BaseContextMenu<T> : IContextMenu 
{ 
    private T executor; 

    public void Exec(Action<T> action) 
    { 
     action.Invoke(this.executor); 
    } 

    public void ExecAsync(Action<T> asyncAction) 
    { 
     // ... 
    } 

? İşte

asyncAction.BeginInvoke(this.executor, IAsyncCallback, object); 

cevap

8

NET asenkron programlama modeline Jeffrey Richter'in makale: Ben BeginInvoke imzası gibi bir şey olduğunu gördük. İşte

http://msdn.microsoft.com/en-us/magazine/cc163467.aspx Beginınvoke nasıl kullanılabileceği bir örnektir:

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); 
    } 
} 

Ve burada ExecAsync geçirilebilir bir geri arama yöntemidir:

private void Callback(IAsyncResult asyncResult) 
{ 
    Action<T> asyncAction = (Action<T>) asyncResult.AsyncState; 
    asyncAction.EndInvoke(asyncResult); 
} 
+0

Bir göz atalım – Raffaeu

+0

Teşekkürler, aradığım şey buydu. Sadece lambda ifadesiyle ilgili bir sorunum vardı, çoklu programlama programında bir kursa ihtiyacım yoktu. Ref için ;-) – Raffaeu

+0

+1. Jeff'in makalesine. Bu gerçekten anlayışlı ve bana çok yardımcı oldu. – IAbstract

2

En basit seçenek:

// 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); 
     } 
    } 
}