views:

119

answers:

4

Hi guys

I'm working on some code that calls a service. This service call could fail and if it does I want the system to try again until it works or too much time has passed.

I am wondering where I am going wrong as the following code doesn't seem to be working correctly... It randomly only does one to four loops...

protected virtual void ProcessAsync(object data, int count)
{
    var worker = new BackgroundWorker();
    worker.DoWork += (sender, e) =>
    {
        throw new InvalidOperationException("oh shiznit!");
    };
    worker.RunWorkerCompleted += (sender, e) =>
    {
        //If an error occurs we need to tell the data about it
        if (e.Error != null)
        {
            count++;
            System.Threading.Thread.Sleep(count * 5000);
            if (count <= 10)
            {
                if (count % 5 == 0)
                    this.Logger.Fatal("LOAD ERROR - The system can't load any data", e.Error);
                else
                    this.Logger.Error("LOAD ERROR - The system can't load any data", e.Error);
                this.ProcessAsync(data, count);
            }
        }
    };
    worker.RunWorkerAsync();
}

Cheers Anthony

UPDATE:

I've switched my code over to use ThreadPool.QueueUserWorkItem instead... Since doing this my problems have gone away and semantically I can do the same thing. Thanks for all your help guys.

+1  A: 

This must be the most bizarre retry mechanism I saw. Can you make a cleaner one? Avoid recursive calls unless they are simple and easy to maintain, because it can easily lead to mistakes.

Lex Li
"Avoid recursive calls unless they are simply and easy to maintain, because it can easily lead to mistakes." -- That's quite the generalization. In *this case* I agree recursion isn't the way to go. But some problems are more naturally solved with recursion, and I don't see why recursion would be any harder to maintain than iteration.
Robert Fraser
It isn't recursive, ProcessAsync has already exited by the time the event runs.
Hans Passant
+4  A: 

I've modified your code slightly and don't have any issues running through 10 iterations (VS 2008 Express) which leads me to this: Is this the actual code and if not, are you sure you've sent enough to reproduce the issue?

If I were to venture a guess, I would say that the count you're sending it varies such that count % 5 > 0 and that there's an exception getting thrown in Logger.Fatal.

private void button1_Click(object sender, EventArgs e)
{
    ProcessAsync("beer", 1);
}

protected virtual void ProcessAsync(object data, int count)
{
    var worker = new BackgroundWorker();
    worker.DoWork += (sender, e) =>
    {
        throw new InvalidOperationException("oh shiznit!");
    };
    worker.RunWorkerCompleted += (sender, e) =>
    {
        //If an error occurs we need to tell the data about it
        if (e.Error != null)
        {
            count++;
            //System.Threading.Thread.Sleep(count * 5000);
            if (count <= 10)
            {
                if (count % 5 == 0)
                    this.Logger.Fatal("LOAD ERROR - The system can't load any data - " + count.ToString(), e.Error);
                else
                    this.Logger.Error("LOAD ERROR - The system can't load any data - " + count.ToString(), e.Error);
                this.ProcessAsync(data, count);
            }
        }
    };
    worker.RunWorkerAsync();
}

SomeLogger Logger = new SomeLogger();

class SomeLogger
{
    public void Fatal(string s, Exception e)
    {
        System.Diagnostics.Debug.WriteLine(s);
    }

    public void Error(string s, Exception e)
    {
        System.Diagnostics.Debug.WriteLine(s);
    }
}

EDIT: A Suggestion
Put a try-catch around the call to Logger.Fatal and see what happens.

EDIT: Another suggestion
I suspect you aren't sharing enough code for us to help. The key to success here would be to isolate the problem in a dummy project that only has enough code to show the failure. I'd be willing to bet that if you can do that, you most likely wouldn't need to post this as question here...

You can start with my assumptions and should see that this works just fine. Then start changing the generalized code into what you're actually using (I'd start with the real implementation of Logger.Fatal). The error will likely become pretty obvious in short order.

Austin Salonen
I agree - the poster's code works fine in VS 2010 with Console.Writeline() calls instead of the Logger class calls. I'd put my money on Austin's idea of Logger.Fatal() throwing an exception.
Simon Chadwick
Does it work when you put the sleep back in... Its important that the sleep is there as if the last call failed its unlikely that the next one would work right after...
vdh_ant
yes, the code definitely works. Is there third party dependency, apart from the `Logger` that Simon already mentioned?
Nayan
It works just fine with the `Sleep` call; it's just easier to test without it.
Austin Salonen
I've tried putting the try catch around it and after the 4th exception is thrown it doesn't even seem to run RunWorkerCompleted...
vdh_ant
Are you sure it's not your Delay that is making you wait?
Nayan
+1  A: 

I don't see an obvious reason. However, your RunWorkerCompleted event would normally run on the UI thread. And hang it for as long as 55 seconds. That cannot be desirable.

There isn't any reason I can think of why you'd not just loop in the DoWork method with a try/catch block.

Hans Passant
I agree. Maybe he can use a separate thread to avoid UI hang-ups?!
Nayan
He's already got a thread, he doesn't need another one.
Hans Passant
I didn't mean that. If he can, he should separate UI and background tasks.
Nayan
A: 

There is one thing that is really bad!

Within your RunWorkerCompleted() you call a Thread.Sleep(). Due to the fact, that this function will be processed within the GUI thread your application is going to freeze!

Please don't call Thread.Sleep() within any event of the BackgroundWorker cause all of them will be processed within the GUI thread.

So this is maybe not a real solution to your current problem, but definitely something you should care about.

Update
To start something after a given time period you should take a look into the various timer classes. Each of them has it's own pros and cons. For a more insight view you should take a look into this article.

Oliver
Is there another way to set up the process to automatically try again in x time period...
vdh_ant