【问题标题】:cast delegate type to Delegate and call EndInvoke将委托类型转换为 Delegate 并调用 EndInvoke
【发布时间】:2011-03-13 18:35:19
【问题描述】:

我继承了一些我正在尝试重构的冗长、重复的代码。其中的骨架如下:

private void startThreads() 
{ 
    RunRemoteCmdDelegate runRemoteCmdDlg = new RunRemoteCmdDelegate(services.runRemoteCommand); 

    List<IAsyncResult> returnTags = new List<IAsyncResult>(); 

    // asynchronously invokes the delegate multiple times
    foreach (...) 
    { 
        returnTags.Add(runRemoteCmdDlg.BeginInvoke(...)); 
    } 

    MonitorTasks(runRemoteCmdDlg, messages, returnTags, invokationCounter); 

} 

private void MonitorTasks(RunRemoteCmdDelegate theDelegate, List<IAsyncResult> returnTags) 
{ 

        foreach (IAsyncResult returnTag in returnTags) {
            MessageType message = runRemoteCmdDlg.EndInvoke(returnTag);
            messages.Add(message)
        } 
}

有许多类包含相同的代码,但都具有不同的委托类型。

我想将 MonitorTasks 方法“拉起”到一个基类中,但它需要使用所有不同类型的委托,例如:

private void MonitorTasks(Delegate theDelegate, List<IAsyncResult> returnTags) 
{ 

        foreach (IAsyncResult returnTag in returnTags) {
            MessageType message = runRemoteCmdDlg.EndInvoke(returnTag);  // DOESN'T COMPILE
            messages.Add(message)
        } 
}

我不能在基本 Delegate(或 MulticastDelegate)类型上调用 EndInvoke(),那么我该如何编写这个方法呢?我需要以不同的方式解决这个问题吗?

我用的是C#3.5,有什么方法可以使用Func、Action等,而且还能调用EndInvoke?

【问题讨论】:

    标签: c# multithreading delegates


    【解决方案1】:

    您可以使用反射来访问委托的EndInvoke() 方法:

    using System.Reflection;
    
    private void MonitorTasks(Delegate theDelegate, List<IAsyncResult> returnTags) 
    { 
        MethodInfo endInvoke = theDelegate.GetType().GetMethod("EndInvoke",
            new Type[] { typeof(IAsyncResult) });
        foreach (IAsyncResult returnTag in returnTags) {
            MessageType message = (MessageType) endInvoke.Invoke(theDelegate,
                new object[] { returnTag });
            messages.Add(message);
        } 
    }
    

    请参阅this blog,了解更一般的、即发即弃的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多