tags:

views:

574

answers:

2

Is this the best way to handle file moving in a windows service? we have many files that get matched and moved, but an end user may have the file opened at the time of moving.

This is what the code currently says:

Do While IO.File.Exists(OriginalFilePath)

    Try
     IO.File.Move(OriginalFilePath, BestMatchPath)
    Catch ex As IO.IOException
     Log(TraceLevel.Warning, "The file '{0}' was unable to be moved (probably opened by someone)", OriginalFilePath)
     Threading.Thread.Sleep(1000)
    End Try

Loop

Is there a better way to manage this? I have thought of threading it to allow the process to continue, but currently i am unsure if this is viable, as the rest of the process might need the files path to be accurate.

+2  A: 

A suggestion: in the service Start() method, activate a System.Timers.Timer to periodically run your file moving loop, without the Sleep(1000) call. This way, a file that was not moved in the current run will not block the move of other (unlocked) files. Problematic files will have a chance to be moved in later trials. Adjust timer interval to fit your needs.

@Andy have thought of threading - a Timer is an effective way to deal with threading. A service process is a proper place for repeated execution of code sections. Note that the loop without Sleep(1000) will not block.

gimel
I don't believe that a thread at sleep will block any other process.
kenny
I don't think that's what he meant. As implemented, if a file is locked the service will completely block (itself) and not process any other files.
GalacticCowboy
+2  A: 

As this is a Windows service, and depending on the number of files you're trying to move concurrently, I would consider using a background thread for each file move. If you use the BackgroundWorker type, you can marshal any exception back to the main thread and then wait for X minutes before trying to move the file again.

Normally I wouldn't advocate a multi-threaded solution, but in this case there's no shared state between the threads, so it's much easier to control any threading issues.

As for doing some other task that depends on all of the file moves being successful, you can join to the background threads so that you're aware when they've all finished.

RoadWarrior