简体   繁体   中英

How To: Cancel Web Service Function Request

This might be discussed elsewhere but I can't find it. I have a .Net Web Service that has a function that loops through a date range and runs calculations and updates records in a database. If you give this said function a long date range, it can take quite some time to complete. This being the case, I need a way to stop this function.

Is there a way of making the web service function call run in a identified thread so that I can cancel that thread if need be? Or am I over or under thinking this? I am using C# .Net Web Page with jQuery to perform the AJAX calls to the web Service function. Any help will be greatly appreciated.

Add a Cancel() method to your web service that sets a state variable. Then, simply have your long running operation periodically check this variable and stop if its set (with appropriate protection, of course).

You need to web service methods:

  1. StartCalculation(parms) which spanws a long running operation and returns an ID
  2. CancelCalculation(ID) which cancels the calculation by terminating the long running operation.

The implementation of the 'long running operation' depends on your service hosts (IIS, Windows Service, etc.).

Sure, you can do that. If you're using .NET 4, you can easily cancel a task:

 CancellationTokenSource cts = new CancellationTokenSource();
 var processingTask = Task.Factory.StartNew(() =>
    {
          foreach(var item in StuffToProcess())
          {
               cts.Token.ThrowIfCancellationRequested();

               // Do your processing in a loop
          }
    });

  var cancelTask = Task.Factory.StartNew(() =>
      {
           Thread.Sleep(/* The time you want to allow before cancelling your processing */);
           cts.Cancel();
      });

   try
   {
       Task.WaitAll(processingTask, cancelTask);
   }
   catch(AggregateException ae)
   {
       ae.Flatten().Handle(x =>
          {
               if(x is OperationCanceledException)
               {
                   // Do Anything you need to do when the task was canceled.
                   return true;
               }

               // return false on any unhandled exceptions, true for handled ones
          });
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM