I have a couple of services running, A and B (both are web api) and an http client. This is the sequence of events I want accomplish asynchronously:
- Client calls A and passes an object O as parameter,
- A begins async process (P1) to do something with O,
- While P1 is running A sends asynchronous message to B [P2] (which may take a while) for B to do something with it. Essentially A is now the client of B
[ this is the important part ]
- As soon as P1 is finished doing its work I want A to send OK response back to the calling client,
- I don't want to make the client wait until B sends its own response to A before A can respond to the client with an OK,
- As far as the client is concerned A does only P1 and that's it, does not care about communication between A and B, it only cares about the results of P1
- A should handle whatever response B may send on its own time at its own pace
- Both P1 and P2 are async methods, which I have already defined and working
6-9 are only for clarification purposes, but how do I accomplish 5?
I'm working with MS stack, VS2013, C#5
Here is pseudo code I'm trying to implement:
// this is the clinent and where it all begins
class Class1
{
static void Main()
{
using (var client = new HttpClient())
{
var o = new SomeObject();
var response = client.PostAsJsonAsync(api, o);
Console.Write(response.Status);
}
}
}
// this one gets called from the client above
class ServiceA
{
public async Task<IHttpActionResult> Post([FormBody] SomeObject someObject)
{
// this one I want to wait for
var processed = await ProcessSomeObjectA(SomeObject some);
// now, how do I call SendToService so that this POST
// will not wait for completion
SendToService(someObject);
return processed.Result;
}
private async Task<bool> ProcessSomeObjectA(SomeObject some)
{
// whatever it does it returns Task<bool>
return true;
}
private async Task<IHttpActionResult> SendToService(SomeObject someObject)
{
using (var client = new HttpClient())
{
var o = new SomeObject();
var response = await client.PostAsJsonAsync(api, o);
return response.StatusCode == HttpStatusCode.OK;
}
}
}
class ServiceB
{
// this gets called from ServiceA
public async Task<IHttpActionResult> Post([FormBody] SomeObject someObject)
{
return (await ProcessSomeObjectB(someObject))) ? Ok() : BadResponse();
}
private async Task<bool> ProcessSomeObjectB(SomeObject some)
{
// whatever it does it returns Task<bool>
return true;
}
}