views:

35

answers:

2

We may be accustomed to code below:

if(File.Exists(xxx))
{
  //I am here
  using(var streamReader = new StreamReader("xxx"))
  {
    ...
  }
}

Well, the potential problem is that, the file xxx may be deleted by another thread (or process) when the code reaches "//I am here". Thus, the using block will throw exception.

Anyway to avoid this? (I don't want to have an ugly try-catch around using.) Any pattern or common practice to solve this kind of 'thread/process safety' problem for an unmanaged resource?

Thanks,

+1  A: 

Use a try/catch. They are prettier than they look.

If you control all applications that access the folder, you can use a named mutex (a cross-appdomain-semaphore). If this is a generally accessible folder, the problem is not really preventable.

Henk Holterman
+1  A: 

Of course you can use system-wide mutexes to introduce synchronization over system resources. But this is a bit overkill here and anyway you can't prevent other applications/processes that do not care about these mutexes from deleting the file.

So I'd rather recommend you to use try/catch over StreamReader.

Vitaliy Liptchinsky