INTERNET APPLICATION DEVELOPMENT
MID MARKET ERP DEVELOPMENT
by Derek Du
If a WebAPI service takes a long time to complete, the caller -- the client side -- may timeout waiting for a response. There are several options to solve this issue, you can increase the timeout limit on the client side and web server side, or use a more persistent connection method like WebSocket and SignalR.
I propose a different way to avoid the timeout issue that allows the client's side to proactively check the result instead of passively waiting. The idea is pretty intuitive – since the client side times out on waiting for a response, why not disconnect and check the result later? So, the solution is to disconnect with the client side as soon as the request is received, and a WebAPI service enables the client to check for the processing status. This way, the client does not need to keep the connection open until the processing completes or times out. It can simply calls back every five seconds to check the processing result.
Here is some sample code on how to achieve this. First, we create a Task class:
We then create a class to store tasks and to handle creation, retrieval, and deletion of tasks:
Up to this point, we have our "backend" built. Now, we create a WebAPI method to accept the request from the client side, and a method for the client side to check a task’s status:
To avoid client side timeout when calling WebAPI, we chose an approach that enables the client side to check the results actively. Although it makes the client side a bit more complex, it is a reliable way to handle WebAPI calls that run a long time and also provides much more flexibility to the client side.
This article originall appeared in Derek's blog, Stuff.