Reputation: 30924
I'm trying to wrap my head around the new async/await functionality in combination with webapi.
What I would like to do is the following:
I don't want to wait on the work from B before I can return a OK message to the request that was sent to A. I would like to be able to call A and get OK back ASAP while the work is still being completed on B.
Is this even possible? If so, what would be a correct way to design something like this?
Thanks for any pointers you might give me.
Upvotes: 0
Views: 141
Reputation: 1220
You probably want to respond to the caller with a response code of 202 (accepted) to indicate to the client that some other processing is ongoing. Then if your client needs additional feedback it could do a long poll, or you could implement a websocket, etc.
Upvotes: 1
Reputation: 5566
You start the background work and respond immediately. The async pattern is only to be used in case you have to respond in any way on the result of the long running task and prevent blocking of the calling thread. i.e:
public bool ControllerAMethod(byte[] somedata)
{
Task.Factory.StartNew(() =>
{
ControllerB.SendData(somedata);
});
return true;
}
Upvotes: 1
Reputation: 2685
Just an assumptioin based out of the async/await concept explained by John Skeet. The async/await pattern uses continuations which maintain the state machine. Basically the frame work is supposed to execute the instructions till the end of the synchronous methods.
When it encounters the async call instructions, it invokes it and if the result is readily available goes to the next steps and does the processing. If it does not have the result immediately after the call, it returns back from the method leaving this to be taken care by the framework. So in your case, I think practically it would return immediately if you have no code. But if you have any long running code, it should return leaving the job to the background framework thread but result may come back later.
If your objective is to make sure you don't block the foreground, then this will be achieved with the first controller itself. But even in your case, the second controller wouldn't block the UI. To your question on whether this is right or wrong, I am sure because you may have some reasons why you are thinking of such a pattern.
There are numerous experts here. Correct me if my interpretation is wrong, please:)
Upvotes: 1
Reputation: 149598
What you want is to trigger a "Fire and Forget" semantics on your call.
If you're using .NET 4.5.2, you can use HostingEnvironment.QueueBackgroundWorkItem
to register and queue work on a ASP.NET Threadpool thread.
If you're on previous versions, you can use BackgroundTaskManager
by Stephan Cleary.
Note this has nothing to do with async-await
.
An example would look like this:
public HttpResponseMessage Foo()
{
HostingEnvironment.QueueUserWorkItem(() => { /* offloaded code here */ });
return Request.CreateResponse(HttpStatusCode.OK);
}
Upvotes: 4