Jasper Manickaraj
Jasper Manickaraj

Reputation: 837

How to use cancellationToken in MVC3?

I am newbie to MVC3. In my project MVC3, i'm using threading for import excel sheet to Database and it works perfectly. I have a doubt on the following, 1) How to stop the thread using CancellationToken?? -- In my MVC# form i have the following.. 2 buttons named Cancel and Import respectively. 2) On Import button Submit event i have the following code.

    //Button Click on Import
    [HttpPost]
    public ActionResult FinalImport(FormCollection collection)
      {
            Task.Factory.StartNew(() =>
            { 
               //My Coding To Import

            } , tokenSource.Token);

            return null;
      }

    CancellationTokenSource tokenSource=new CancellationTokenSource();

    //Button Click on Cancel 
    public void CancelToken()
    {
        tokenSource.Token.ThrowIfCancellationRequested();
        tokenSource.Cancel();
      //  return null;
    }

Note: If i click the import button and the While running the task and then click the Cancel button menas nothing will happen.. How to cancel the execution of the thread process. Please help me to achieve this...

Upvotes: 0

Views: 1279

Answers (2)

Jasper Manickaraj
Jasper Manickaraj

Reputation: 837

Finally I have find the solution.

1) Need to initialize CancellationTokenSource as static.

2) Need to Dispose the CancellationTokenSource Object tokensource in the CancelToken Method
Call.

public static CancellationTokenSource tokenSource; 

[HttpPost]
    public ActionResult FinalImport(FormCollection collection)
      {
            tokensource=new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            { 
                 if (ts.IsCancellationRequested)
                            {
                                break;
                            }
               //My Coding To Import

            } , tokenSource.Token);

            return null;
      }



    //Button Click on Cancel 
    public void CancelToken()
    {

        tokenSource.Cancel();
        tokensource.Dispose();
    }

That's it.. Happy Coding....!!!!

Upvotes: 0

Colin Mackay
Colin Mackay

Reputation: 19175

Because the web is essentially a stateless environment, you need some way to persist the cancellation token from one request to another. The FinalImport and CancelToken methods are separate requests. The application treats each one as being brand new, as if it has never seen the previous request before. You are writing the code as if it is running in a stateful environment.

The following could work for you.

Here are the high level steps:

  • Create your tokenSource in the FinalImport method.
  • Add the token source to a dictionary with a unique key that will persist requests. (Say one declared as a static, so that it is global to the entire application).
  • Pass back the key to the browser.

When the user presses the cancel button in the browser:

  • Have the browser send the key in the request.
  • In your CancelToken look up the dictionary with the key that the browser sends with the request.
  • Use the tokenSource from the dictionary to cancel the task.
  • Remove the token from the dictionary.

You should also, as the last thing in your task, remove the token from the dictionary (otherwise they will just build up and up and up until you run out of memory)

If, for any reason, the process running your web application should fail and IIS has to restart it, then you will lose your dictionary. IIS will restart your process for a variety of reasons such as memory pressure (e.g. it things you may have a memory leak and it creates a new process to work with), or because its been 29 hours since the last time it restarted it, or because any number of things. If you are running a web garden or web farm, then you won't be guaranteed to be returned to the same process on each request, so the dictionary may not be available.

While I realise this is not a code solution, I hope this helps understanding the problem domain a little better.

Upvotes: 3

Related Questions