views:

83

answers:

3

I have a process that calls an event when its done.

void DoProcess()
{
    ...
    ...
    // Call finished event
    OnFinished();
}

I want to run this process many times.

My first idea was to recall the process each time the 'Finished' event was called.

void obj_Finished()
{
    DoProcess();        
}

Would this mean that the stack would get bigger and bigger? since the 'Finished' event would call its self wich would call the 'Finished' event etc...

Could I use anouther thread in some way to avoid this problem?

Is there a better deisgn pattern that i coudl use?

I would like the code to be quite efficient, however, I do like using events :)

+2  A: 

Assuming WinForms or WPF: Use a BackgroundWorker.

You can run DoProcess in a simple loop and call Updateprogress to execute your event (synchronized).

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        var worker = sender as BackgroundWorker;

        while (true) // or something
        {
            DoProcess();
            worker.ReportProgress(0, null);
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        OnFinished();
    }

This assumes that DoProcess does not touch the UI, it is running on another thread. ProgressChanged runs on the Main thread.

Henk Holterman
A: 

Yeah, this would cause an infinite loop, unless you put logic in place that causes the final DoProcess() to not raise an event or exits the process before the event is raised.

Unless there is a good reason to work with events here, I'd simply put DoProcess() calls in an iteration loop.

Unless you really HAVE to work with events and in that case I'd create a controller object that handles the Finished events and based on certain conditions either has another DoProcess() performed or simply raises an event that lets the whole world know that all the DoProcess() thingies that had to be executed are done.

Anton
A: 

It is not clear to me what DoProcess and the event handler are doing, but assuming nothing complicated I do not see a reason why not to do it simply like this:

while (condition)
{
  DoProcess();
}