异常由最外层的try/catch处理.windows服务
本文关键字:catch 处理 windows 服务 try 异常 | 更新日期: 2023-09-27 18:12:24
抛出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
.
为什么?
如果这是一个LINQ API暴露IQueryable
你不会得到一个错误,由于延迟执行,LINQ到SQL实现通常使用。
为了防止它,你必须在第一个方法中调用.ToList()
, FirstOrDefault()
等。这可以确保查询确实已经对数据源执行了。
解决方案:
var documents = connection.QueryDocuments(revision).ToList();
foreach(var document in documents) {
if(fetchedDocuments > fetchQuota) return;
// [...]
}