网络中断时使用 Directory.Exists 在网络文件夹中

Using Directory.Exists on a network folder when the network is down(网络中断时使用 Directory.Exists 在网络文件夹中)

本文介绍了网络中断时使用 Directory.Exists 在网络文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我公司的代码库包含以下 C# 行:

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

bool pathExists = Directory.Exists(path);

在运行时,字符串 path 恰好是公司 Intranet 上文件夹的地址 - 类似于 \companycompanyFolder.当从我的 Windows 机器到 Intranet 的连接启动时,这工作正常.但是,当连接断开时(就像今天一样),执行上面的行会导致应用程序完全冻结.我只能通过使用任务管理器来关闭应用程序.

At runtime, the string path happens to be the address of a folder on the company's intranet - something like \companycompanyFolder. 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.

当然,在这种情况下,我宁愿让 Directory.Exists(path) 返回 false.有没有办法做到这一点?

Of course, I would rather have Directory.Exists(path) return false in this scenario. Is there a way to do this?

推荐答案

对于这种情况,无法更改 Directory.Exists 的行为.在引擎盖下,它通过网络在 UI 线程上发出同步请求.如果网络连接因中断、流量过多等而挂起……也会导致 UI 线程挂起.

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<bool> func = () => Directory.Exists(path);
Task<bool> task = new Task<bool>(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;
}

这篇关于网络中断时使用 Directory.Exists 在网络文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:网络中断时使用 Directory.Exists 在网络文件夹中

基础教程推荐