Chibueze Opata
Chibueze Opata

Reputation: 10034

Why does CreateFile take forever?

I have a thread in my program which tries to CreateFile in order to lock a usb device, however, sometimes instead of failing, it takes forever. Has anyone else encountered this problem? Is there any way I can set a timeout for this function? The code is something like this:

string file = @"\\.\" + DriveLetter[0] + ":";
handle = CreateFile(filename, GENERIC_READ, FILE_SHARE_WRITE, IntPtr.Zero, 0x3, 0, IntPtr.Zero);

Thanks.

Upvotes: 1

Views: 1036

Answers (2)

Chibueze Opata
Chibueze Opata

Reputation: 10034

The taking forever seemed to have been some sort of conflict with the main form thread.

Eventually, I moved the locking functions containing the CreateFile operation to a separate thread where it wouldn't compete with the UI thread and it works fine now.

Upvotes: 1

user2299169
user2299169

Reputation:

You want to lock it to make it inaccessible -as a device- or to "block" detaching it (as e.g. it's a pen)?
EDIT: sorry I'm not allowed to add comment :S
Anyways. If the locking is important you can do that easily with devcon: http://support.microsoft.com/kb/311272
, and a sample code:
http://www.programmersheaven.com/mb/dotnet/337951/337951/programatically-enable--disable-usb-port-using-cnet/
in case you don't want to use the exe with params all the time.

Upvotes: 1

Related Questions