Search code examples
c#.netasynchronousyieldfeedback

Using yield without return type


I have a big long looping procedure like this:

public void Process()
{
    bool done = false;
    do {
        //do stuff
    }while (!done);
}

that I'd like to chop into bits and have the calling routine display my progress in some sort of UI. It's a class library, so the caller may be anything (Console App, WinForms, WebApp, ...).

It would be easiest if I could do:

public void Process()
{
    bool done = false;
    do {
        //do stuff
        yield return;
    }while (!done);
}

So the caller could keep calling the method until it's done.

This smells more like a job for BackgroundWorker, but that seems "wrong" for a Console App... I won't always NEED multithreading. Or does it? I mean, yeah, I could just have the console's main thread just wait for it to finish.

My question is: Can I use the "piecemeal" deferred execution functionality of "yield return" without actually returning something?


Solution

  • In short, no.

    yield return has to return something.

    http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

    The Process method should have a return type of IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. You may return dummy objects if you really want to use yield.

    You might want to investigate different ways to report progress to the caller.