VB .Net - 反射:从加载的程序集中反射的方法在调用方法之前执行。为什么?

时间:2010-05-17 20:55:08

标签: vb.net reflection

当我动态加载程序集,然后从中调用一个方法时,我似乎是在调用它的方法中的代码之前从Assembly执行方法。它似乎没有像我预期的那样以串行方式执行。任何人都可以阐明为什么会发生这种情况。下面是一些代码来说明我看到的内容,some.dll程序集中的代码调用名为PerformLookup的方法。为了测试,我将类似的MessageBox类型输出与“PerformLookup Time:”作为文本。我最终看到的是:

First: "PerformLookup Time: 40:842"

Second: "initIndex Time: 45:873"

Imports System
Imports System.Data
Imports System.IO
Imports Microsoft.VisualBasic.Strings
Imports System.Reflection

Public Class Class1
    Public Function initIndex(indexTable as System.Collections.Hashtable) As System.Data.DataSet
        Dim writeCode As String
        MessageBox.Show("initIndex Time: " & Date.Now.Second.ToString() & ":" & Date.Now.Millisecond.ToString())
        System.Threading.Thread.Sleep(5000)
        writeCode = RefreshList()
    End Function

    Public Function RefreshList() As String   
        Dim asm As System.Reflection.Assembly
        Dim t As Type()
        Dim ty As Type
        Dim m As MethodInfo()
        Dim mm As MethodInfo
        Dim retString as String
        retString = ""

        Try
            asm = System.Reflection.Assembly.LoadFrom("C:\Program Files\some.dll")
            t = asm.GetTypes()
            ty = asm.GetType(t(28).FullName) 'known class location
            m = ty.GetMethods()
            mm = ty.GetMethod("PerformLookup")
            Dim o as Object
            o = Activator.CreateInstance(ty)
            Dim oo as Object()   
            retString = mm.Invoke(o,Nothing).ToString()
        Catch Ex As Exception       
        End Try

        return retString
    End Function
End Class

我在write方法的末尾添加了一个flush语句,即使我有一个StreamReader.Close()调用。结果相同。以下是我输入的调试语句的一些输出,以便进一步尝试和诊断。在initIndex我有

write(timestamp)  
save(file)  
write(save success)  
write(saved value)  
write(timestamp)  
write(file create / file modified times)   
sleep(5 seconds)  
invoke(assembly method)  
write(timestamp)  

在装配方法中,我有:

write(timestamp)  
sleep(5 seconds)  //yes, two 5 second sleeps between write and read  
read(file)  
write(file value)  
write(timestamp)  
write(file create / file write times)  

这是我的initIndex logfile输出:

17:732  
True  
A/P  
17:732  
5/17/2010 11:59:30 AM / 5/18/2010 7:49:17 AM  
22:748  

这是Assembly类logfile的输出:

12:670  
CASH  
17:685  
5/17/2010 11:59:30 AM / 5/18/2010 7:41:20 AM  

2 个答案:

答案 0 :(得分:0)

日期时间不像您想象的那么精确,您可能只是看到了这种不完美。

答案 1 :(得分:0)

所以你把新的时间写回文件然后重新阅读?您是否正在刷新输出流以确保数据已写入文件而不是仅缓存为惰性写入?