5

I am developing a Windows Forms Application to perform few operations on a device connected via USB. For All operations like Read, Write and other things, we have a custom library.

Write operation is done when User hits a button.

To read, a Separate thread is created. Problem with available library is that the Read call is blocking and has INFINITE Timeout.

In case of connection failure, this thread stucks at Read function call as this function breaks only if it recieves data.

What could be the way to Kill this thread in such scenario? Thread.Abort() is not working.

I am using C# for this programming.

Aleksandar Toplek
  • 2,792
  • 29
  • 44
Swanand
  • 4,027
  • 10
  • 41
  • 69
  • 1
    If the "custom library" does not provide *any* means to cancel a blocking read on a failed connection, you should throw it away and use something different, honestly. – Clemens Aug 23 '12 at 11:07
  • I know....I wish I could... But Same is the case with default Serial Port class of C# ... Read operation will stuck on failed connection, if I set Timeout to Infinte. – Swanand Aug 23 '12 at 11:39
  • You could try closing the "handle" to whatever you are trying to read from...then the Read will be cancelled I should guess...and your thread depending on how it's written may exit. – Colin Smith Aug 23 '12 at 11:55

1 Answers1

1

That Read method of yours probably calls native code so thread can't abort. There is no way (at least that I am familiar with) to abort thread that uses COM interop. You could look why is Read method blocking thread in the first place. Try to check for requirements before calling Read method.

Take a look at this question: Abort call to unmanaged DLL

Community
  • 1
  • 1
Aleksandar Toplek
  • 2,792
  • 29
  • 44
  • Running it in a separate process was what I was considering. I was also thinking you MIGHT be able to run the dangerous code in another app domain which I thought you might be able to "shoot in the head" as well but... it suffers from the same failure to abort a thread problem see: http://msdn.microsoft.com/en-us/library/system.appdomain.unload.aspx – John Sobolewski Aug 23 '12 at 12:01
  • Thanks for the idea! But how to run a only one thread in Different Process? OR Running a function as a Different process?? – Swanand Aug 24 '12 at 05:30
  • You could create another application that deals with COM interop (usb communication) and start that application as Process. You can then communicate with that process via Pipes http://msdn.microsoft.com/en-us/library/system.io.pipes.aspx – Aleksandar Toplek Aug 24 '12 at 10:40