【问题标题】:exception gets handled by the outermost try/catch. windows services异常由最外层的 try/catch 处理。窗口服务
【发布时间】:2014-07-10 14:31:16
【问题描述】:

抛出ThirdPartyException(我不知道他们的代码是如何工作的)异常的函数:

private void RequestDocuments(/* arguments... */) {
    while(true) {
        var revision = lastRevision;
        var fetchedDocuments = 0;

        try {
            foreach(var document in connection.QueryDocuments(revision)) {
                if(fetchedDocuments > fetchQuota) return;

                container.Add(document);
                ++fetchedDocuments;

                Logger.Log.InfoFormat("added document (revision: {0}) into inner container", document.Revision);
            }

            Logger.Log.Info("Done importing documents into the inner container");
            return;
        }
        catch(Exception ex) {
            if(ex is ThirdPartyException) {
                // handle this in a certain way!
                continue;
            }
        }
    }
}

这个函数在工作线程中被调用,如下所示:

private void ImportDocuments() {
    while(!this.finishedEvent.WaitOne(0, false)) {
        try {
            var documents = new List<GohubDocument>();
            RequestDocuments(remoteServerConnection, documents, lastRevision, 100);
        }
        catch(Exception ex) {
            // here is where it really gets handled!!!?
        }
    }
}

异常仅在最外层(在ImportDocuments 方法内)try/catch 处理。

这是为什么呢?

【问题讨论】:

  • 使用编辑 + 高级 + 格式化文档。您现在很有可能会在代码中看到错误。
  • 那么至少用它来改进你的代码sn-p的格式。糟糕的缩进给方式太多不好的线索。
  • 你在第二个捕获中得到什么异常类型? “以某种方式处理这个!”可以扔了。
  • 现在您发布了无法编译的代码。 catch 语句位于 try 块之外,而 continue 语句位于 while() 循环之外。显然,您的真实代码中有些东西非常糟糕,并且您在记录它方面做得很差。肯定是这个问题的根本原因。
  • @HansPassant 感谢您对代码格式的更正。尽管你是对的,但除了嘲笑我之外,你什么也没做?

标签: c# .net multithreading exception windows-services


【解决方案1】:

如果这是公开 IQueryable 的 LINQ API,您不会因为 LINQ to SQL 实现通常使用的延迟执行而收到错误。

为了防止它,您必须在第一个方法中调用.ToList()FirstOrDefault() 等。这样可以确保查询确实已针对您的数据源执行。

解决方案:

var documents = connection.QueryDocuments(revision).ToList();
foreach(var document in documents) {
    if(fetchedDocuments > fetchQuota) return;
    // [...]
}

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    相关资源
    最近更新 更多