Skip to main content
 首页 » 编程设计

c#之使用 BeginInvoke 调试异常

2024年02月23日22jackei

我有以下方法:

protected void OnBarcodeScan(BarcodeScannerEventArgs e) 
{ 
    if (BarcodeScan != null) 
    { 
        //BarcodeScan.BeginInvoke(e, null, null); 
        BarcodeScan(e); 
    } 
} 

当我尝试进入上述方法时,它工作正常。我能够介入并超越该方法的所有部分。

但是,如果我切换注释(所以 BarcodeScan(e) 被注释掉并删除 BarcodeScan.BeginInvoke(e, null, null) 上的注释,那么我不能进入 OnBarcodeScan 方法的任何部分(即 if (BarcodeScan != null) 上的断点没有被击中。

我也试着把一些调试语句放在那里。但只要 begin invoke 调用在那里,它就不会让我进入该方法。

我检查了输出,当我尝试介入时它说:

A first chance exception of type 'System.NotSupportedException' occurred in ScannerTest.exe Step into: Stepping over method without symbols 'Symbol.Marshaller.SymbolMessageWindow.WndProc' Step into: Stepping over method without symbols 'Microsoft.WindowsCE.Forms.MessageWindow._WndProc'

为什么在有BeginInvoke的情况下整个方法无法执行?

任何帮助都会很棒!

请您参考如下方法:

Compact Framework 不支持异步委托(delegate)调用(即 BeginInvoke)。

至于为什么调试器连方法都不打断,我相信是因为以下几点:

  • BeginInvoke/EndInvoke 方法由 C# 编译器生成(它是 required to do this ),标记为“ native ”。这意味着 CLR 将提供实现。
  • 紧凑型框架 CLR does not provide the implementation .
  • 当 JIT 编译器第一次执行一个方法时,它会查找它可能调用的所有方法(加载其他程序集等)。
  • 由于 CLR 不支持 Delegate.BeginInvoke,任何调用它的方法都无法进行 JIT 编译,因此无法执行。
  • NotSupportedException 在首次调用 OnBarcodeScan 时抛出(JIT 编译器尝试编译它但失败)。这就是调试器无法进入的原因。