schultz
schultz

Reputation: 316

I do not understand this code from MSDN

The following code is from this MSDN article a link, what I do not understand is in the Appendix B, all the way down in the article.

private IEnumerator<ITask> OnStartup()
{
    rst4.ServiceTutorial4State state = null;

    yield return Arbiter.Choice(
        _clockPort.Get(GetRequestType.Instance),
        delegate(rst4.ServiceTutorial4State response)
        {
            state = response;
        },
        delegate(Fault fault)
        {
            LogError(null, "Unable to Get state from ServiceTutorial4", fault);
        }
    );

    if (state != null)
    {
        ServiceTutorial6State initState = new ServiceTutorial6State();
        initState.InitialTicks = state.Ticks;

        PartnerType partner = FindPartner("Clock");
        if (partner != null)
        {
            initState.Clock = partner.Service;
        }

        Replace replace = new Replace();
        replace.Body = initState;

        _mainPort.Post(replace);
    }

    yield return Arbiter.Choice(
        _clockPort.Subscribe(_clockNotify),
        delegate(SubscribeResponseType response) { },
        delegate(Fault fault)
        {
            LogError(null, "Unable to subscribe to ServiceTutorial4", fault);
        }
    );
}

Why does the code have two return states, It has two yield statements, Will both work? I'm truly sorry if O'm wasting your time with silly questions, but if someone is able to answer the question this is the place...

Upvotes: 1

Views: 127

Answers (2)

SJuan76
SJuan76

Reputation: 24780

You can read as:

1) When the method is called, an IEnumerator is returned

2) The first time the Next method of the enumerator is called, it will return the result of the first yield return

3) The following times the Next method is called, it will "continue" the execution of this code where it left and stop to return the following yield return

4) If the end of method is reached or yield break is reached, it will signal that the enumerator has run over all the elements.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499860

Why does the code have two return states, It has two yield statements, Will both work?

Yes. yield return will yield the given value to the method which is asking for the "next" value... but when the next value is asked for again, the method will continue from where it previously yielded.

You might want to read my article on iterator blocks or the MSDN page about them.

Upvotes: 4

Related Questions