Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-cooperative cancellation of an asynchronous operation

In my Windows Form application I need to call a long-running operation of a 3rd party math library (Accord.NET). During computation I want to keep my GUI responsive and also give the user the possibility to cancel the long-running operation.

Is there a way to execute that function in a background thread and giving the user the possibility to cancel it? Note that the long-running function I'd like to call is in an external library and does not accept a CancellationToken (otherwise I could easily use ThreadPool's QueueUserWorkItem, for example). So I am looking for a way to non-cooperatively cancel the operation.

like image 493
Robert Hegner Avatar asked Dec 05 '25 05:12

Robert Hegner


2 Answers

I'd say you have three choices.

One, spin the calculation into it's own thread. This will keep the UI responsive. Instead of a cancel button, just let the user know the action the are about to take can't be stopped once stared.

Two, spin the calculation into it's own thread just like above; however, pretend to cancel it by simply reducing the threads priority. You can let the calculation keep going, but just stop reporting progress in your main thread. When it's done just throw away the results.

Three, put the calculation into it's own appdomain/process. If desired, kill that external process.


There are good and bad things about each one.

like image 55
NotMe Avatar answered Dec 07 '25 17:12

NotMe


huh? Just use a Thread and a worker method.

Thread thread = new Thread(MyWorkerMethod);
thread.Start();

thread.Abort();


void MyWorkerMethod() {
    // do anything you want in here
}
like image 31
ChrisB Avatar answered Dec 07 '25 18:12

ChrisB