Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel async task via web request?

Here is the scenario: On user login I start a task which is listening to IMAP idle for mail notifications and it has live connection with the client via signalr(kind of push notification). Now the problem is how do i cancel this task? i.e. user cancel push notification or log out..

EDIT: as per my understanding for example if 5 users logged on to the site there are 5 tasks running? so how do i cancel individual tasks.

like image 296
Iternity Avatar asked Sep 07 '12 21:09

Iternity


People also ask

How do I cancel async tasks?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

Can we cancel async task?

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

Should I dispose CancellationTokenSource?

You should always dispose CancellationTokenSource .


1 Answers

The asynchronous worker must be modified to support cancellation

http://www.csharp-examples.net/cancel-asynchronous-method/

You could also use the background worker which is a bit less complicated http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx

A problem I have encountered when you send a cancel to an external source (DB, app) which has already started a job, if it does not support canceling, you may have to wait until it finishes.

EDIT: I've never done this with MVC but found a good article on 'Using a Cancellation Token' for an asycn process which takes a CancellationToken parameter in MVC4. http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4 hope it helps.

like image 62
hagensoft Avatar answered Oct 13 '22 10:10

hagensoft