0

I got a requirement to implement a long running process in asynchronously. I have done the implementation using Task.Run() everything worked without any issues. However the requirement got changes and now they want 'cancel' feature of any ongoing async task. if I explained the requirement more simple form; I have a button, text box and a list box. when a user enter something in the text box and click on the button , it should fetch data from db and populate the list box with db results (assume this is a long running process) if the user change his mind and enter something again in the text box and click on the button, it should stop the current running task, clear the list box and should start the task (fetching and displaying data) with the new values entered in his second attempt.

I tried to use cancellation token for this but didn't get succeeded. I would be grateful if somebody can help me with this.

svick
  • 236,525
  • 50
  • 385
  • 514
RSF
  • 510
  • 6
  • 18
  • 1
    What was the problem with the cancellation token? – Boklucius Mar 23 '14 at 19:10
  • 2
    Please post your code. You won't get any useful answers if you make everyone guess what you did wrong. – Chris Ballard Mar 23 '14 at 19:31
  • 1
    Yet another "I tried this and it didn't work" question on SO... man, this trend makes me want to give up writing answers. How hard is it to *post a specific error message and the code directly related to the issue*? We can't read you mind and we can't see your screen. Please be more thorough. – NathanAldenSr Mar 23 '14 at 21:01

1 Answers1

2

Using a CancellationToken does not magically cancel a running Task. The code running inside the task needs to be aware of the token and actively check it for cancellation. All methods provided to your by the framework does this already so you might not be used to this. However, it sounds like you have written your own method which accepts a CancellationToken alongside these lines

public Task Method(CancellationToken ct)
{
 // do some database work here
}

In this case you should look at the library you use for communicating with the database to see if it supports CancellationToken. If it does, then pass it along to the library. If it does not, then you can manually check the token after the database operation finishes like this

public Task<int> Method(CancellationToken ct)
{
 // do some database work here
 ct.ThrowIfCancelled();
 // return DB result here
}

With this approach you won't be cancelling your DB request, but at least you won't be returning results, and the code which invoked the request will be able to handle the cancellation.

If you happen to be using a library such as EntityFramework then you will be able to provide your CancellationToken to some of the requests and thus potentially saving the database from doing wasted work as well as being able to cancel the task immediately.

Kasper Holdum
  • 12,993
  • 6
  • 45
  • 74