Avatar of cp30
cp30
Flag for United Kingdom of Great Britain and Northern Ireland asked on

How to wrap important database update in .net

Hi all,

I have a .net (vb) program (windows service) that gets to a stage where it needs to update a sql server by calling a stored procedure.  This works fine but occasionally the sql server could be unavailable for a few seconds due to connectivity issues.  This update is absolutely critical so I want to wrap it in some code to retry in case of failure to communicate with the sql server.  Is there any best practice or examples for adding this resilient retry functiionality?

Thanks in advance
.NET ProgrammingMicrosoft SQL Server 2008Visual Basic.NET

Avatar of undefined
Last Comment
nepaluz

8/22/2022 - Mon
Bardobrave

Assign a boolean return value to the method that calls the stored procedure. If the execution works return true, otherwise return false.

On your main code, when calling the method do:

storedProcExecuted = false;
while(not storedProcExecuted)
    storedProcExecuted = callYourStoredProcMethod(yourParams);

This way your method will retry until it executes and returns true.
It's pretty rough but functional and easy.
jogos

Try catch to catch the unable to connect or timeout.

But when building a loop for retrial, don't make it running forever.
Nasir Razzaq

Within your method that executes the stored procedure, you can execute a simple Select Count to test the connection and keep trying (for a configurable number of times) to connect if you get error. Something like

Private Function ...
For i as integer = 0 to 10
  try
    'code to test connection
    connected=true
    exit for
  catch
  end try
  if connected then
     'code to execute stored procedure
  end if
End Function
Your help has saved me hundreds of hours of internet surfing.
fblack61
cp30

ASKER
Hi,

I'm not keen on something that runs indefinitely Bardobrave's suggestion, while the update is critical and I want to retry, I'd rather it fails after x number of retries and logs an exception rather than lock up the whole application because it's got into an infinite loop.

Problem with CodeCruiser's suggestion is that I don't think I can assume that just because I tested the connection a few lines back, that it will still be available.

Thinking that a limited loop with Try/Catch seems best suggestion so far...something like this....

retryExecuteSP:

 Try
            iRetry += 1

            Dim cmd As New SqlCommand("spLB_updateThreadInfo", conn)

            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("threadIinfo", threadInfo)

            conn.Open()
            cmd.ExecuteNonQuery()

            Return True

        Catch ex As Exception

            If iRetry < 6 Then
                Threading.Thread.Sleep(1000)
                GoTo retryExecuteSP
            End If

            Return False
        Finally
            conn.Close()
        End Try

    End Function

Open in new window


Any comments on that? So it should try 5 times and then return false if still no joy
Nasir Razzaq

Yeah that would do the job as well.
jogos

You already implemented the comment I wanted to make: a waiting period between retrial.

Some comments on exception
- you only need to retry when there is something like 'not connected ..', 'time out' ...
- you don't close connection .... but you reopen it in second attempt , even for timeout it wasn't necessary
- here you have overview, but don't you want to rollback everything if your last statement errored
- what if you get an error 'unable to allocate space', or 'FK violation' -> you retry and after 6 times you return false .... and how do you know what error?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
nepaluz

Threading.Thread.Sleep(1000) will block (won't it?) Why not start a timer and get it to fire off the retry?
cp30

ASKER
Hi jogos,

- you only need to retry when there is something like 'not connected ..', 'time out' ...
yes, I will add in more specific checking when I make live

you don't close connection .... but you reopen it in second attempt , even for timeout it wasn't necessary
But I thought this would be closed by the finally block which is always executed

here you have overview, but don't you want to rollback everything if your last statement errored
It's actually a simple update that the sp performs which should either work or not, and I can add some error trapping in the sp itself, it's mainly the potential connectivity issue that worries me.

what if you get an error 'unable to allocate space', or 'FK violation' -> you retry and after 6 times you return false .... and how do you know what error?
Yes, I will add some kind of logging to catch the full exception details in case of 6 times failing.

Cheers
cp30

ASKER
Hi nepaluz,

Threading.Thread.Sleep(1000) will block (won't it?) Why not start a timer and get it to fire off the retry?

This code will be in a multi-threaded windows service so I don't think it matters if I block the current thread as all other threads will carry on, (I think), and the current thread can't carry on until it knows if the sp has been executed as it will carry out more tasks once the sp is successfully called.

Hope that makes sense, and others can comment if thread.sleep is the correct call to make.

Cheers
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER CERTIFIED SOLUTION
nepaluz

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
cp30

ASKER
Thanks for that.  What is the benefit of using the timer over the sleep?

Cheers
nepaluz

Hmmm ........!! Get back to you on that.