Fire-forget and One-Way Calls in ASP.NET WebApi

跟風遠走 提交于 2019-12-10 13:49:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!