I have this piece of code that drives me mad.
FUNCTION DiskInDrive(CONST DriveNumber: Byte): BOOLEAN;
VAR ErrorMode : Word;
BEGIN
RESULT:= FALSE;
ErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
TRY
if DiskSize(DriveNumber) <> -1 { %%%% THIS IS VERY SLOW IF THE DISK IS NOT IN DRIVE !!!!!! }
THEN RESULT:= TRUE;
FINALLY
SetErrorMode(ErrorMode);
END;
END;
It checks if a disk is ready to be used (and also if the provided drive letter corresponds to a valid disk).
The problem is that when I try to access a disconnected network drive (network folder mapped as drive), it freezes for about 10-30 seconds.
The code is in the constructor of a component I made.
How can I check a drive without waiting that long?
As far as I know, it’s simply unavoidable that doing something with a network drive may lock up the calling thread while Windows tries to access the network drive. It’s one of those leaky abstractions that Joel Spolsky talks about.
Your best bet is to do your drive checking from a separate thread so that it doesn’t lock up the UI. (Delphi 2009’s generics or Jon Schemitz’ MsgWaits library can simplify the necessary multithreading code.)