[SOLVED] How to end a function that hangs sometimes?


I have written a function f like this:

void f()
   f1();   // Pre-Work
   f2();   // the actual work 
   f3();   // Post-Work

f1 and f3 are my own functions, but f2 comes from a library I have no control of. f is called periodically from some controller.

All works fine, but once a week f2 hangs, and does not return for unknown reasons. What is the design pattern to handle this? Probably, f should be run in an extra Task, or can I use async/await pattern? What is with memory that might be allocated in f2?


if f2 actually hangs and never returns, there are a few things that can be done.

Start by ensuring that the method is used correctly, i.e. that any parameters are always correct, and there is no synchronization issue going on, i.e. ensure the library is used in a thread safe way.

If that does not help, contact the authors of the library. It might help if you can reproduce the issue, so writing a minimal reproducible example might help. Callstacks, memory dumps and other supporting information might also help. If the library is open source you might have the option of fixing the issue yourself.

If nothing else works, move the call to a separate process. This will let you close the process without cooperation from the function. There is some more details in What’s wrong with using Thread.Abort(). This will add some complexity, but there libraries that can make this easier. A message queue like NetMq would probably work, you might also consider something like gRPC, there are ton of options to chose from.

Answered By – JonasH

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.