views:

182

answers:

2

I'm testing the existence of a file in a remote share (on a Windows server). The underlying function used for testing is WinAPI's GetFileAttributes, and what happens is that function can take an inordinate amount of time (dozens of seconds) in various situations, like when the target server being offline, when there are rights or DNS issues, etc.

However, in my particular case, it's always a LAN access, so if the file can't be accessed in less than 1 seconds, then it typically won't be accessible by waiting dozens of seconds more...

Is there an alternative to GetFileAttributes that wouldn't stall? (apart from calling it in a thread and killing the thread after a timeout, which seems to bring its own bag of issues)

+1  A: 

One cool thing about delegates is you can always BeginInvoke and EndInvoke them. Just make sure the called method doesn't throw an exception out since [I believe] it will cause a crash (unhandled exception).

AttributeType attributes = default(AttributeType);

Action<string> helper =
    (path) =>
    {
        try
        {
            // GetFileAttributes
            attributes = result;
        }
        catch
        {
        }
    };
IAsyncResult asyncResult = helper.BeginInvoke();
// whatever
helper.EndInvoke();
// at this point, the attributes local variable has a valid value.
280Z28
So basically, no hope outside wrapping the API call in a thread? I was hoping for a solution outside threads, because killing a thread at a timeout isn't "clean" (by experience, bad things can happen), and ignoring stalled threads could potentially lead to a whole lot of stalled threads...
Eric Grange
Sorry, it also seems I mistakingly assumed you were working in .NET (answered a few of those before this). If the API doesn't have an asynchronous and/or timeout version available, then the threading solution may be the only reliable solution.
280Z28
+1  A: 

The problem isn't GetFileAttributes really. It typically uses just one call to the underlying file system driver. It's that IO which is stalling.

Still, the solution is probably easy. Call CancelSynchronousIo() after one second (this obviously requires a second thread as your first is stuck inside GetFileAttributes).

MSalters