Using Directory.Exists on a network folder when the network is down

后端 未结 2 733
误落风尘
误落风尘 2021-02-07 12:26

My company\'s code base contains the following C# line:

bool pathExists = Directory.Exists(path);

At runtime, the string path happ

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 13:01

    There is no way to change the behavior of Directory.Exists for 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

    Func func = () => Directory.Exists(path);
    Task task = new Task(func);
    task.Start();
    if (task.Wait(100)) {
      return task.Value;
    } else {
      // Didn't get an answer back in time be pessimistic and assume it didn't exist
      return false;
    }
    

提交回复
热议问题