0

I have a C# WebAPI that runs a fairly complex algorithm when called from the client. The algorithm is a bit unpredictable in the amount of time it can take - usually 5-10 seconds but occasionally up to 90 seconds (I'm working on this). As the user manipulates the UI on the client side, I'd like to continuously send up requests to the API to begin processing, such that when the user enters a different section of the UI, the API request has completed and I can immediately display the results of the (most recent) API call.

It's only important to finish the calculations the final time they are run, so I'd like new requests to this API method to replace the old requests if any are running, rather than spawn a new thread in the API.

In case that's unclear:

  1. User manipulates UI.
  2. UI sends RequestA to WebAPI (WebAPI begins calculations)
  3. User manipulates UI again
  4. UI sends RequestB to WebAPI
  5. WebAPI is not finished with RequestA yet, so RequestA is killed and RequestB begins

Is there a way to do this, or if not (or if it's terrible practice) is there a different way to create this kind of functionality?

topher
  • 328
  • 1
  • 8
  • How are you making web api call? Using jQuery Ajax? If yes try aborting previous ajax request - http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery – malkam Mar 27 '15 at 05:59
  • There is no built-in way to abort the processing of requests I'm aware of. You can abort a request on the client side, but that only means the client stops waiting for an answer. If you can tell different users apart, I'd suggest to implement some sort of processing registry, where processing tasks are registered per user. If a user starts another processing task, check if they have one already and abort it if so. First and foremost, though, make sure that this is a real issue and not an imaginated one. Don't optimize unless you can't prove it's needed. – bstenzel Mar 27 '15 at 07:13
  • I think this is a terrible idea from the start and you should examine the reasons why you need/want to do this. The project I'm working on at the moment and if anything is going to take more than 2 seconds then we put it on a queue to be run by a separate job handler process then use signalr to tell the client that the job is done. We never cancel a job once it's started. – matt_lethargic Mar 27 '15 at 08:48

0 Answers0