简体   繁体   中英

c# FileSystemWatcher fires on multiple clients

I'm using a FileSystemWatcher to watch a directory. I created a _Created() event handler to fire when a file is moved to this folder. My problem is the following:

The files in this directory get created when the user hits a "real life button" (a button in our stock, not in the application). The FileSystemWatcher take this file, do some stuff in the system and then delete it. That wouldn't be a problem when the application runs only once. But it is used by 6 clients. So every application on every client is trying to delete it. If one client is too slow, it will throw an exception because the file is already deleted.

What I'm asking for is: Is there a way to avoid this?

I tried using loops and check if the file still exists, but without any success.

while (File.Exists(file))
{
    File.Delete(file);
    Thread.Sleep(100);
}

Can someone give me a hint how it could probably work?

Design

If you want a file to be processed by a single instance only (for example, the first instance that reacts gets the job), then you should implement a locking mechanism. Only the instance that is able to obtain a lock on the file is allowed to process and remove it, all other instances should skip the file.

If you're fine with all instances processing the file, and only care that at least one of them succeeds, then you need to figure out which exceptions indicate a genuine failure and which ones indicate a failure caused by the actions of another instance.

Locking

To 'lock' a file, you can open it with share-mode FileShare.None . This prevents other processes from opening it until you close the file. However, you'll then need to close the file before you can delete it, which leaves a small gap during which another instance could open the file.

A better solution is to create a separate lock file for that purpose. Create it with file-mode FileMode.Create and share-mode FileShare.None and keep it open until the whole process is finished, including the removal of the processed file. Then the lock file can be closed and optionally removed.

Exception

As for the UnauthorizedAccessException you got, according to the documentation , that means one of 4 things:

  1. You don't have the required permission
  2. The file is an executable file that is in use
  3. The path is a directory
  4. The file is read-only

1 and 4 seem most likely in this case (if the file was open in another process you'd get an IOException ).

如果要在同一台计算机上的多个客户端之间同步访问,则应使用命名互斥锁

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM