1

I have the following code:

var op = ThreadPool.RunAsync(delegate { _model.HeapSort(); });

Is there a way to stop this thread, for example when I push a "Cancel" button? I have tried op.Cancel() but nothing seems to happen.

4
  • 1
    Assuming HeapSort doesn't implement cancellation as well, not really, no.
    – Servy
    Feb 24, 2014 at 21:32
  • You'll have the exact same problem there too, for the exact same reason.
    – Servy
    Feb 24, 2014 at 21:49
  • So is there any way I can do it?
    – Daniel
    Feb 24, 2014 at 21:51
  • 2
    Have an implementation of HeapSort that provides cooprative cancellation, i.e. accepts a CancellationToken and checks it periodically. The only other real alternative is to have the code continue moving on to doing whatever is "next" even though the sorting isn't actually done, which isn't technically cancellation.
    – Servy
    Feb 24, 2014 at 21:53

2 Answers 2

0

In your implementation of HeapSort, there must be a flag to stop the current thread.

If you are doing a loop for example:

while(!cancelThread)
{
   ... // Your iterative sort algorithm here
}

Then if you set that cancelThread variable to true, then your Thread will end. CancellationToken structure is used for this kind of thread control.

2
  • 1
    CancellationToken isn't just a boolean flag though. Most important it ensures the proper synchronization techniques such that marking the token as cancelled will actually be "realized" when it's read from another thread. This is an easy thing to overlook when just using a regular bool and can cause pretty major problems.
    – Servy
    Feb 24, 2014 at 22:03
  • @Servy, that is right. Just giving the idea, you know. Feb 24, 2014 at 22:07
0

ThreadPool.RunAsync accepts a delegate of type WorkItemHandler:

public delegate void WorkItemHandler(IAsyncAction operation)

Its only argument IAsyncAction is derived from IAsyncInfo. There's IAsyncInfo.Status property. I presume it's set to AsyncStatus.Canceled when IAsyncInfo.Cancel is called (untested).

So, you could check periodically if operation.Status == AsyncStatus.Canceled inside your delegate, and throw OperationCancelledException.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.