Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

windows - How To: Prevent Timeout When Inspecting Unavailable Network Share - C#

We have some basic C# logic that iterates over a directory and returns the folders and files within. When run against a network share (\serversharefolder) that is inaccessible or invalid, the code seems to 'hang' for about 30 seconds before returning back from the call.

I'd like to end up with a method that will attempt to get folders and files from the given path, but without the timeout period. 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...