【问题标题】:Exception swallowed when doing drag and drop拖放时吞下异常
【发布时间】:2010-11-01 11:35:21
【问题描述】:

我有一个 WinForms 应用程序,我在其中进行 2 个 TreeView 之间的拖放操作。

在某些时候,我想拒绝底层业务实现中的操作,所以我抛出了一个异常。我可以在输出窗口中看到异常,但问题是我在 UI 中看不到它并且它不会崩溃。

异常去哪儿了?

下面是一些描述问题的代码:

private TreeView tvLeft;
private TreeView tvRight;
private Dictionary<string, int> dico = new Dictionary<string, int>();

void tvLeft_DragDrop(object sender, DragEventArgs e) {

  if (e.Data.GetDataPresent(typeof(TreeNode))) {

    var tnSource = (TreeNode) e.Data.GetData(typeof(TreeNode));
    var tnDestination = tvLeft.GetNodeAt(tvLeft.PointToClient(new Point(e.X, e.Y)));

    // if I drag-drop the same node twice, there sould be an Exception
    // since the key is already in the dictionary...
    // ...but I get no Exception in the UI, the Application.ThreadException
    // or Appomain.CurrentDomain.UnhandledException handlers
    dico.Add(tnSource.Name, (new Random()).Next());

  }

}

【问题讨论】:

  • 你可能想分享一些代码

标签: c# winforms exception drag-and-drop


【解决方案1】:

我在网上找到了这个解释:

即使在同一个应用程序中进行拖放,拖放也是通过标准的 OLE 拖放机制来处理的。从 OLE 的角度来看,它正在处理两个应用程序,即源和目标,并将它们适当地解耦。由于 OLE 比 .NET 存在的时间要长得多,因此 OLE 没有 .NET 异常的概念,因此无法将异常从目标传回源。即使可以,为什么源要关心目标不能执行丢弃? 如果要在 DragDrop 事件期间处理异常,则必须在 DragDrop 事件处理程序中处理它,它不会传播到该事件处理程序之外,因为在源和目标之间存在托管到非托管到托管的代码转换。

请参阅here 问题后的第一个答案。

【讨论】:

    【解决方案2】:

    异常可能发生在某处的后台线程上。您需要为 AppDomain.CurrentDomain.UnhandledException 或 Application.ThreadException 事件创建处理程序。

    有关更多详细信息,请参阅here

    【讨论】:

    • 我已经创建了两个处理程序,但异常没有显示在它们中的任何一个中。还有其他的吗?
    • 在 Visual Studio 中,点击 Debug->Exceptions,然后勾选“Common Language Runtime Exception”旁边的“thrown”框。这应该使调试器在抛出异常后立即进入您的代码,并且您可以使用 F10/F11 沿着它所遵循的路径前进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2018-05-26
    • 2012-03-06
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多