如何:在检查不可用的网络共享时防止超时 - C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/726602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To: Prevent Timeout When Inspecting Unavailable Network Share - C#
提问by
We have some basic C# logic that iterates over a directory and returns the folders and files within. When run against a network share (\\server\share\folder) that is inaccessible or invalid, the code seems to 'hang' for about 30 seconds before returning back from the call.
我们有一些基本的 C# 逻辑,可以遍历目录并返回其中的文件夹和文件。当针对无法访问或无效的网络共享 (\\server\share\folder) 运行时,代码似乎在从调用返回之前“挂起”了大约 30 秒。
I'd like to end up with a method that will attempt to get folders and files from the given path, but without the timeoutperiod. In other words, to reduce or eliminate the timeout altogether.
我想以一种方法结束,该方法将尝试从给定路径获取文件夹和文件,但没有超时期限。换句话说,完全减少或消除超时。
I've tried something as simple as validating the existence of the directory ahead of time thinking that an 'unavailable' network drive would quickly return false, but that did not work as expected.
我尝试了一些简单的方法,比如提前验证目录是否存在,认为“不可用”的网络驱动器会很快返回 false,但这并没有按预期工作。
System.IO.Directory.Exists(path) //hangs
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); //hangs
Any suggestions on what may help me achieve an efficient (and hopefully managed) solution?
关于什么可以帮助我实现有效(并希望管理)解决方案的任何建议?
采纳答案by Al Katawazi
Place it on its own thread, if it doesn't come back in a certain amount of time, move on.
把它放在自己的线程上,如果它在一定时间内没有回来,继续前进。
回答by mqp
Perhaps you could try pinging the server first, and only ask for the directory info if you get a response?
也许您可以先尝试 ping 服务器,然后仅在收到响应时才询问目录信息?
回答by Kevin Dance
See...
看...
Faster DirectoryExists function?
...for a way of setting the execution time for Directory.Exists
...一种设置 Directory.Exists 执行时间的方法
回答by Jonatha ANTOINE
You can use this code:
您可以使用此代码:
var task = new Task<bool>(() => { var fi = new FileInfo(uri.LocalPath); return fi.Exists; });
task.Start();
return task.Wait(100) && task.Result;