'What is the best practice to handle long external process in ASP.NET page?
An example will be something like: User clicks a button on a webpage I created with ASP.NET. My app calls an API hosted on a third party server. The user sees a spinning icon/Please wait message, while my app is waiting the third party server to return the results to me, which may take a minute.
The solution isn't limited to what version of .NET.
Solution 1:[1]
In most cases, since you can't wait for code behind to finish (since the web page is stuck up on the server), and ONLY after ALL your code behind is done, can the page THEN travel back down to client side, be re-freshed, JavaScript starts running, and THEN the results are displayed client side. In effect code behind NEVER interacts directly with the user, but only with the web page and ONLY while the page has been posted up to the server, travels up to the server. Your code behind can then in this very short time, modify values on the page, and then the while page is sent back to the client.
So, what this means is you have to adopt ajax. That means you write JavaScript client side, and they can call a web service you setup on your web site. In such cases then, no post-back of the page has occurred, and there are "many" features of JavaScript that allow you to do this. (such as promise, await, etc.). So, most web service calls by nature are asynchronous (you don't know how long you have to wait). So, yes, this is quite much the best practice, and how this common type of issue is to be approached.
So, in effect you not use code behind on the web page for this, but create a web service (web method) for the given page, or a separate aspx page with your required web service calls. Such pages do NOT have use of the controls on your current page, don't have use of ViewState, but can use session().
So, just google making web service calls in asp.net.
You can however also start a new process thread, and have it talk to that "other service". And then say drop in a timer (and even a up-date panel ). It could trigger every one second, and poll say a database (or session()) values to determine when done, and then update the web page, and then stop the timer.
So, the timer trick means you can often avoid writing a web service, and then having to wire up the ajax calls to web methods in JavaScript. (this is the correct way, but the timer + starting another process can work quite well also, and in most cases eliminates the need for a web service and ajax calls).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |