Does yield return work across service boundary?

Viewed 211

I have a WCF service with this contract and implementation:

[OperationContract]
IEnumerable<string> GetData(int value);

public IEnumerable<string> GetData(int value)
{
           int i = 0;
            while (i++ < value)
            {
                Console.WriteLine($"returning {i}th item");
                yield return $" Item:{i}";
            }
        }
}

When GetData is called by client the yield does not seem to work. All the items are returned in one go instead of one by one.

1 Answers

Indeed. Because the data is serialized to go over the wire, so the serializer calls the method, materializes the result and writes it to a byte stream to send over the network.

If you'd put that class in the same assembly as your client and call it directly instead of over a service pipeline, it would work.

It does make a lot of sense to not work over serialized connections, one of them being that your other endpoint might not even be .NET at all and might not know that IEnumerable<T> is a special snowflake in terms of execution order.

Related