问题
I totally understand that HTTP world is not the best choice for one-way calls and that WebApi is designed best for HTTP verbose communications. No doubt, WCF is the winner here. But, what if you already have an ApiController with a bunch of verbs exposed and at some point you needed to have a single one-way call too? And you don't want to host/maintain another service (WCF) for that.
Task<HttpResponseMessage> response = client.PostAsJsonAsync<Log>("api/log", log)
If you don't handle the response then you've got something similar to fire-and-forget. Is this the only way in WebApi or there's another solution?
回答1:
Why not just call like this and ignore the returned task?
client.PostAsJsonAsync<Log>("api/log", log);
I do this with all my calls and use a handler in the response pipeline to deal with responses if necessary.
回答2:
Your best bet is to start a new Task and send the response immediately rather than returning the task:
public void PostDoFireAndForget() // and NOT public Task PostDoFireAndForget()
{
Task.Factory.StartNew
(() =>
{
// ... start the operation here
// make sure you have an exception handler!!
}
);
}
来源:https://stackoverflow.com/questions/13937407/fire-forget-and-one-way-calls-in-asp-net-webapi