Donnerstag, 1. März 2012 00:17ok so i am working a program a lot like google chat only it uses a shared folder between multiple computer so and has a few buttons and timers that makes it automaticaly update a textbox's text to equal the text in a file and then has the text sender box save its text to the file via button. occasionaly if two of the users press send at the same time a error box will appear saying sorring the file "C:\etc.etc" cannot be accessed because another program is accessing it, i want my code to wait a few seconds then retry if this happens instead of showing this error box, is there a way to do this?
Donnerstag, 1. März 2012 09:28Moderator
the common practice is to catch exceptions and then handle the exception. So you could have a loop around the update try and only if no exception occurs, the loop is quit (or after a number of tries).
But you should also think about the design. If you get an exception because of a bad design, then you should look for some other logic to prevent these exceptions.
So one way could be to have this logic:
Each system writes it's own lock file. So if you have the data file "data.txt", you could have
and wen one system wants to update the data.txt file, it is doing this logik:
a) check if there is no lock file
b) if there is no lock file, it writes it's own lockfile.
c) after writing the lockfile, it checks for lockfiles again - if other lockfiles are there, too, we got a racing condition. So the own lockfile is removed, the system waits a short random (!!) time and then starts with a) again.
d) Now data.txt is updated.
e) the lockfile is removed.
You can extend the logik. Only lockfiles that are not older than a specified duration are taken - so if a client crashes with a written lockfile, the system is only blocked for a short time.
With kind regards,