正如 Eric Lippert 在 这篇文章,try/catch
子句中不允许yield return
.
As Eric Lippert described in this article, yield return
is not allowed within try/catch
clauses.
有没有一种很好的方法可以让我得到这样的东西,而不必手动编写自己的IEnumerator
:
Is there a nice way I could get something like this, without having to write my own IEnumerator
by hand:
public IEnumerable<Data> GetData()
{
var transaction = Session.BeginTransaction());
try
{
IQuery q = CreateQuery(session);
foreach (var result in q.Enumerable())
yield return ProjectResult(result); // <-- doesn't work
session.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
finally
{
transaction.Dispose();
}
}
我只是像这样更改事务处理逻辑:
I'd just change the transaction-handling logic like this:
public IEnumerable<Data> GetData()
{
var transaction = Session.BeginTransaction();
bool rollback = true;
try
{
IQuery q = CreateQuery(session);
foreach (var result in q.Enumerable())
{
yield return ProjectResult(result);
}
rollback = false;
session.Commit();
}
finally
{
if (rollback)
{
transaction.Rollback();
}
transaction.Dispose();
}
}
或者,如果您的事务支持除非已提交,否则处理意味着回滚"的想法:
Or if your transaction supports the idea of "dispose means rollback unless it's commited":
public IEnumerable<Data> GetData()
{
using (var transaction = Session.BeginTransaction();
{
IQuery q = CreateQuery(session);
foreach (var result in q.Enumerable())
{
yield return ProjectResult(result);
}
// Commits the tnrasaction, so disposing it won't roll it back.
session.Commit();
}
}
这篇关于try/catch 块的收益回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!