My company’s code base contains the following C# line:
bool pathExists = Directory.Exists(path);
At runtime, the string path happens to be the address of a folder on the company’s intranet – something like \\company\companyFolder. When the connection from my Windows machine to the intranet is up, this works fine. However, when the connection goes down (as it did today), executing the line above causes the application to freeze completely. I can only shut the application down by killing it with the Task Manager.
Of course, I would rather have Directory.Exists(path) return false in this scenario. Is there a way to do this?
There is no way to change the behavior of
Directory.Existsfor this scenario. Under the hood it’s making a synchronous request over the network on the UI thread. If the network connection hangs because of an outage, too much traffic, etc … it will cause the UI thread to hang as well.The best you can do is make this request from a background thread and explicitly give up after a certain amount of time elapses. For example