当网络关闭时,在网络文件夹上使用Directory.Exists [英] Using Directory.Exists on a network folder when the network is down
问题描述
我公司的代码库包含以下C#行:
My company's code base contains the following C# line:
bool pathExists = Directory.Exists(path);
在运行时,字符串 path
是公司内部网上的文件夹的地址 - 例如 \\company\companyFolder
。当我的Windows机器到内部网络的连接是,这工作正常。但是,当连接断开时(如今天),执行上面的行会导致应用程序完全冻结。
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.
当然,我宁愿有 Directory.Exists(path)
return false
。是否有办法这样做?
Of course, I would rather have Directory.Exists(path)
return false
in this scenario. Is there a way to do this?
推荐答案
没有办法改变 Directory的行为。存在此场景
。引擎盖下,它在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!