Bob Loblaw
Bob Loblaw

Reputation: 68

WCF REST - Is it possible to return response without ending the execution?

As you'll most likely figure it out, I'm not very experienced with async operations in general (only used Android's AsyncTask).

This is the outline of a WCF REST POST method; I'll use this image to hopefully explain what I'm trying to achieve.

enter image description here

The FirstJob saves some stuff to the database.

SecondJob reads what was saved in the database and does some work with the data.

The client does not care about what happens in SecondJob and just wants to receive the response from FirstJob.

So the two jobs don't need to run in parallel as SecondJob depends on FirstJob; the SecondJob would ideally run in a separate thread/context(?) or similar.

From what I've noticed, the second job does start in a separate thread, the execution reaches the return statement while the 2nd job is running, but the request does not end until SecondJob finishes.

Upvotes: 2

Views: 381

Answers (3)

VMAtm
VMAtm

Reputation: 28355

I suggest you not to rely on the IIS to handle your background task as it can shut down it without waiting. I suggest you to create a windows service application, which will accept the requests for a second jobs, via another WCF binding or database requests or something else.

You can get the results of the second jobs with another request from your controller, as @PhillipH stated.

Upvotes: 1

Bob Loblaw
Bob Loblaw

Reputation: 68

The thing I was trying to do was actually working in the first place, but the visual studio debugger fooled me. I tested again without the debugger, but with a Tread.Sleep(60000) and it looks like it behaves as expected. The SecondJob keeps running in the background after the api call returned the response.

Upvotes: 0

PhillipH
PhillipH

Reputation: 6222

I'd personally treat the second job as a separate POST operation and call the second job POST from the controller. The controller is the controller for the first job and can return the correct status from the first job; it just happens to call a POST out to a second endpoint while doing it.

The benefit of this approach is that the second job doesn't even need to be on the same IIS (in an NLB farm it could be anywhere) so you get load balancing thrown in for free. Alternatively the "second job server" can be on a specific URL reserved just for this kind of background processing task.

Upvotes: 3

Related Questions