0

We have a function that opens a file (file is custom .oxr file). Issue is that sometimes the file is corrupted and the program halts and does not proceed and come out of the function.Hence the entire program is affected.

I am trying to develop a method that will time out the function after certain seconds. I have implemented this using threading. Here is the concept:- I am calling the function as a thread by using 'thread.join' method that waits for certain seconds for threaded function to execute. After timeout, I am just aborting the thread. So, the call returns back to code after the point where thread was called. It works as expected!

Is this concept good practice?

variable
  • 8,262
  • 9
  • 95
  • 215
  • No, that's not a good practice. Aborting a thread inside your own process is bad. If you can't fix your function, run this unstable operation in a separate child process and kill it instead. – noseratio Feb 28 '14 at 07:42
  • Here's how to do it right: http://stackoverflow.com/questions/13513650/how-to-set-timeout-for-a-line-of-c-sharp-code – Carsten Feb 28 '14 at 07:57
  • @Aschratt, cooperative cancellation is not an option here, unless the OP can fix his function to deal with corrupted data (what he should have done in the first place). – noseratio Feb 28 '14 at 08:10
  • When the call gets stuck, is it stuck looping or blocked? Assuming blocked, what call is it blocked on? – Martin James Feb 28 '14 at 10:50
  • It is blocked as the custom file with .oxr format is corrupted. So what happens is that the file internally opens in code but gets stuck at an internal messagebox which does not popup while accessing via in code... Did you come across corrupted .doc files.. Microsoft has created methods that detect and timeout when file cannot be opened due to corruption reasons... But this is our custom code.. – variable Feb 28 '14 at 11:50

1 Answers1

1

You have multiple problems with this concept:

  1. It is hard to implement with async code, because the thread may change during execution, for example: The method makes a web request (Thread 1), and the callback can be executed by another thread (depending on your synchronization context).

  2. Threads are expensive. It takes a lot of time to create or stop a thread and each thread consumes about 4 MB afaik.

  3. When you abort the thread you leave your objects in an undefined state, you cannot predict what it is happening when you call a method on them.

  4. You cannot stop asynchronous operations with thread aborting.

In my opionion it is okay to do it if you have no other option and I guess that systems like IIS also have some abort-mechanismus to improve stability, but you should try not do it.

SebastianStehle
  • 2,409
  • 1
  • 22
  • 32