1

I have the following code

        var ts = new CancellationTokenSource();
        var ct = ts.Token;
        object result;
        if (Task.Factory.StartNew(() =>
        {
            result = ThirdPartyLib.ReadFile(path);
        }, ct).Wait(10000))
        {
            return result;
        }
        else
        {
            ts.Cancel();
            return null;
        }

ThirdPartyLib.ReadFile(path) is a method which reads a cad file an object. For some rare files this method will hang and produce 100% cpu usage. That's why I use a Task, wait 10 sec. (which is more than enough time to read the file) and return null if this happens.

My app will continue to run but with high cpu usage until I close it, if I debug the code and look at the tasks they are still running.

I already included the CancellationToken approach to cancel the Task but since I can't implement a cancel logic myself this has no effect (I just included this for demonstration purpose)

tasks

without tasks and with treads I would use thread.Abort(); which is deprecated. Is there a way to forcefully kill a task?

Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189
  • You mean programtically I presume? – Liam Nov 25 '16 at 13:14
  • Nope. Task cancellation is cooperative and you can't cancel what won't cooperate. The only completely reliable way to abort a runaway thread in your application is to exit your entire application. (Aborting a thread is possible, but you can find ample information on why that is terribly unsafe and you might as well exit your process. Even so, if you're willing to risk it it's an option.) – Jeroen Mostert Nov 25 '16 at 13:15
  • This is a tricky one. Your safest bet might be to host the faulty DLL in a separate AppDomain that you can tear down if you need to use `Thread.Abort()`. Or even host it in a separate process and use WCF to call it, and restart the process if the thing hangs. Or ask the vendor to fix their bugs! – Matthew Watson Nov 25 '16 at 13:18

0 Answers0