从try/catch块获得的收益率 [英] Yield return from a try/catch block

查看:105
本文介绍了从try/catch块获得的收益率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如Eric Lippert在

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块获得的收益率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆