views:

62

answers:

3

Hello, I need to merg two PDF files. However sometimes a file might be locked up

I wrote this code, but I'm wondering if it's not the smartest solution:

     private static int FILE_LOCKED_WAIT_PERIOD = 1000;
while (true)
                    {
                        // If the file is in use, IOException will be thrown.
                        // If file is not permitted to be opened because of Permission 
                        // Restrictions, UnauthorizedAccessException will be thrown.
                        // For all other, Use normal Exception.

                        try
                        {
                            inputDocument1 = PdfReader.Open(fileToMerge, PdfDocumentOpenMode.Import);

                            break;
                        }
                        catch (IOException)
                        {
                            Thread.Sleep(FILE_LOCKED_WAIT_PERIOD);
                        }
                        catch (UnauthorizedAccessException)
                        {
                            Thread.Sleep(FILE_LOCKED_WAIT_PERIOD);
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(FILE_LOCKED_WAIT_PERIOD);
                        }
                    }
A: 

You should add a timer so that you sleep for a few clicks before you try the file operation again.

Also you should have counter so you do not wait indefinitely and that you exit after say 15 tries.

Raj More
He's got a Sleep on exception. I do agree that he should have a retry counter.
Pestilence
A: 

Well this depends: 1) Is it a process that is all internal to a system independent of a user? If so you should try to find out what is locking the file and wait for the explicitly. Waiting randomly and then trying over and over again may cause problems on its own.

2) Is it a user that may have the file open? In this case waiting is not helpful since the system could retry all weekend because the user suddenly left for the day. You have no control over user timing. Just tell the user that you cannot do the requested operation because the file is open and have them try again.

Usually waiting for N seconds/minutes is not really a solution. Either you know what the problem may be and poll & resolve the issue or you can't really do anything and just send out notice.

Arthur Thomas
A: 

There is no special function to do this. Actually even if this function exists, some process can still easily lock this file between your "lock check" and "file open"

petkov_d