views:

28

answers:

2

I am uploading thousands of files to a server.

The server connection breaks allot, so I need a way for this console application to be able to recover if the connection fails for a few seconds etc.

My application is simple, it just gets all the files in the c:\uploads folder and then uses a web service to upload the files to the server.

so:

foreach(string file in files) { UploadToServer(file); }

How can I make this so it re-covers in the event of a connection failure? (failures usually last just a few seconds)

A: 

If the files fail to upload, is there an exception that's thrown? If there is, then handle the exception, and either store those files in some kind of container for retrying later, or maybe you can put some kind of Thread.Sleep to wait a little and try again.

BFree
+1  A: 

Use a little helper method that retries the upload several times before throwing in the towel. For example:

static void UploadFile(string file) {
  for (int attempt = 0; ; ++attempt) {
    try {
      UploadToServer(file);
      return;
    }
    catch (SocketException ex) {
      if (attempt < 10 && (
          ex.SocketErrorCode == SocketError.ConnectionAborted ||
          ex.SocketErrorCode == SocketError.ConnectionReset ||
          ex.SocketErrorCode == SocketError.Disconnecting ||
          ex.SocketErrorCode == SocketError.HostDown)) {
        // Connection failed, retry
        System.Threading.Thread.Sleep(1000);
      }
      else throw;
    }
  }
}

Tweak the exception handling code as needed.

Hans Passant