ASP.NET process ajax request during batch process - asp.net

I have ab asp.net form which does a few minutes of processing on postback(button click).I Know this is not ideal but I cannot run this process in an async thread as it uses a control reportviewer which is in Reqd only mode in non primary threads.
Given this limitation as the process is going on I would like to show the status at the client. For this I can fire off Ajax requests to the server to obtain processing status.But since the ASP.NET primary thread for the session is busy rendering the report using the reportviewer control the Ajax requests simply wait until all processing is over. Is there any way to periodically relinquish and regain control of primary thread .This we can allow it to reply to any ajax requests.
I have been researching this problem for a while now.All I need is to render a set of reports in background using the ReportViewer control and provide feedback at client
thanks

That makes no sense. New AJAX calls from the browser can and will be serviced by any of the available threads in the thread pool.
How are you posting the form? You would have to start the process with an AJAX request to generate the reports or else the browser will lock up waiting for the return from a normal form post. This would prohibit additional client side calls to be made to check status.

Related

Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle

We are developing a shopping website where we make use of an external payment processor. When a user choose to pay then the amount and all other required arguments are sent to the 3rd party payment processor. Along with that, we also send a post ipn custom url. This is the url where the payment processor sends back the acknowkedgement.
I want to kickoff a bunch of time consuming operations in the background(asyncronous) when the control is sent back to this url. That way the user who is sitting on the UI of the payment processor does not sit there forever but instead gets the response back instantly. So for the background method to run I have made it async.
The problem is when I run the project the moment the control reaches to call the async method it gives me an exception of
An asynchronous operation cannot be started at this time. Asynchronous
operations may only be started within an asynchronous handler or
module or during certain events in the Page lifecycle. If this
exception occurred while executing a Page, ensure that the Page is
marked <%# Page Async="true" %>.
How do I fix this? Remember the UI is not in my control. It is the UI of the payment processor.
Any help please???
Given your constraints, the best way to achieve what you want is probably to stand up a Windows Service, or some similar independent processing mechanism, and use WCF to pass it your desired processing jobs.
You shouldn't keep this sort of thing on the ASP.NET Server, for all of the reasons that you've already mentioned, and a few others that you haven't mentioned yet.
Further Reading
Long-running ASP.NET tasks

asp.net page wait others server side / asynchrone page

I created an asp.net page for waiting ajax. I have one page creating something that takes 30 seconds. On every step I change a session value.
I have another page for ajax, returning the session value for showing the percentage of creation. But, I dont know why, my ajax page awaits the end of the creation of my first page. So I only get the 100% at the end.
Maybe it's because I use VS development server and not IIS server. If this is the problem, can I change settings of the development server for asynchrone execution?
Or is it something else?
WebForms are not ideal for asynchronous operations.
Add SignalR to your project and use a Hub to push status data back to your page to update the current state of the process you are running Asynchronously.
An example of a technique to perform this type of asynchronous notification is covered in my blog post titled "A Guide to using ASP.Net SignalR with RadNotifications"
Don't use ASP.Net session state to do that. It has an implicit reader/writer lock around it, meaning your other call is probably blocking until your process finishes. You can try storing your status in a database or the cache, but it would probably be better to redesign the interaction.

ASP.NET, asynchronous call to another page, return response immediately

The problem is as follows:
An external server sends incoming SMS messages converted to HTTP requests into my sometimes very time-consuming .aspx page. If no response is returned to the external server in 20 seconds, this is considered as an timeout and the same message is sent to my aspx page again (and maybe again....)
The optimal solution for me would be that the aspx page reads the incoming message (as an HTTP request to the aspx page), starts the processing of the message in another thread, and immediately renders response back to the external server. The external server has no interest in other stuff than the HTTP status (normally 200). When the processing of the message is completed this results in an entry into the log file of the application.
The processing of the message is done by making another web request to an aspx page, and I have tried to use the BeginGetResponse method for the web request, and have created a handler for handling of the completed web request to the processing page. The problem is that the handler seems to not be called, most likely because the aspx page's lifecycle is ended before the asynchrounous web request is completed.
Has anyone any good solution for this problem? I have also looked at the async page model, but this also seems to not be a solution for me because the response should be returned to the external server before the processing of the message is completed.
Regards, Eivind
I'd be very wary of using threads in ASP.Net in this manner. Using them to take advantage of multiple cores is one thing. Using them to set up some kind of concurrent response technique seems like a recipe for disaster. Especially when there is a far more elegant solution.
Your ASP.Net application should merely take the message and toss it in a database and send the success reply. It's job is done. The job of delivering the message should be handled by some kind of service or daemon. Windows Services are kind of a pain to build and maintain so perhaps just a scheduled task that runs every 30 seconds or so checking for queued messages in the DB would suit your purposes just fine.
I've seen a lot of people try to use threads in ASP.Net when they really should just be creating a background service. The results are never as reliable as you would hope.
Async page model is definitely not the solution. Have you tried using the unload event to do EndRequest? I really don't know if that would work but it is worth a try. The most robust way is to use Windows Service to run the async request.

best way to consume a webservice in an asp.net code behind

I'm trying to bind a datasource to a repeater, for instance, to a web service (.asmx from a different website) on page load. The webservice returns a DataSet from an sql call. What is the best way to go about doing this?
Because you're calling another website, you have to contend with two issues (especially if this web service is on somebody else's website or over the public internet). First, there might be a delay to retrieve the data from the other website. Second, the other website might timeout.
At a minimum you should consider an asychronous page request. As this MSDN article states:
If a synchronous request becomes I/O
bound—for example, if it calls out to
a remote Web service or queries a
remote database and waits for the call
to come back—then the thread assigned
to the request is stuck doing nothing
until the call returns. That impedes
scalability because the thread pool
has a finite number of threads
available. If all request-processing
threads are blocked waiting for I/O
operations to complete, additional
requests get queued up waiting for
threads to be free. At best,
throughput decreases because requests
wait longer to be processed. At worst,
the queue fills up and ASP.NET fails
subsequent requests with 503 "Server
Unavailable" errors.
But the best solution is probably to use AJAX. Load the page then make an ajax request to fill the repeater. That way you can have the nice "spinning" graphic or something else happening while you are waiting on the webservice.
Call the webservice, take the result, and bind it to your repeater.
If you can, you might also try to cache the information for a time on your side, if possible to help with overall performance.

BackgroundWorker thread in ASP.NET

Is it possible to use BackGroundWorker thread in ASP.NET 2.0 for the following scenario, so that the user at the browser's end does not have to wait for long time?
Scenario
The browser requests a page, say SendEmails.aspx
SendEmails.aspx page creates a BackgroundWorker thread, and supplies the thread with enough context to create and send emails.
The browser receives the response from the ComposeAndSendEmails.aspx, saying that emails are being sent.
Meanwhile, the background thread is engaged in a process of creating and sending emails which could take some considerable time to complete.
My main concern is about keeping the BackgroundWorker thread running, trying to send, say 50 emails while the ASP.NET workerprocess threadpool thread is long gone.
If you don't want to use the AJAX libraries, or the e-mail processing is REALLY long and would timeout a standard AJAX request, you can use an AsynchronousPostBack method that was the "old hack" in the .net 1.1 days.
Essentially what you do is have your submit button begin the e-mail processing in an asynchronous state, while the user is taken to an intermediate page. The benefit to this is that you can have your intermediate page refresh as much as needed, without worrying about hitting the standard timeouts.
When your background process is complete, it will put a little "done" flag in the database/application variable/whatever. When your intermediate page does a refresh of itself, it detects this flag and automatically redirects the user to the "done" page.
Again, AJAX makes all of this moot, but if for some reason you have a very intensive or timely process that has to be done over the web, this solution will work for you. I found a nice tutorial on it here and there are plenty more out there.
I had to use a process like this when we were working on a "web check-in" type application that was interfacing with a third party application and their import API was hideously slow.
EDIT: GAH! Curse you Guzlar and your god-like typing abilities 8^D.
You shouldn't do any threading from ASP.NET pages. Any thread that is long running is in danger of being killed when the worker process recycles. You can't predict when this will happen. Any long-running processes need to be handled by a windows service. You can kick off these processes by dropping a message in MSMQ, for example.
ThreadPool.QueueUserWorkItem(delegateThatSendsEmails)
or on System.Net.Mail.SmtpServer use the SendAsync method.
You want to put the email sending code on another thread, because then it will return the the user immediately, and will just process, no matter how long it takes.
It is possible. Once you start a new thread asynchronously from page, page request will proceed and send the page back to the user. The async thread will continue to run on the server but will no longer have access to the session.
If you have to show task progress, consider some Ajax techniques.
What you need to use for this scenario is Asynchronous Pages, a feature that was added in ASP.NET 2.0
Asynchronous pages offer a neat
solution to the problems caused by
I/O-bound requests. Page processing
begins on a thread-pool thread, but
that thread is returned to the thread
pool once an asynchronous I/O
operation begins in response to a
signal from ASP.NET. When the
operation completes, ASP.NET grabs
another thread from the thread pool
and finishes processing the request.
Scalability increases because
thread-pool threads are used more
efficiently. Threads that would
otherwise be stuck waiting for I/O to
complete can now be used to service
other requests. The direct
beneficiaries are requests that don't
perform lengthy I/O operations and can
therefore get in and out of the
pipeline quickly. Long waits to get
into the pipeline have a
disproportionately negative impact on
the performance of such requests.
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
If you want using multitheading in your ASP page, you might using simple threading model like this:
{
System.Threading.Thread _thread = new Thread(new ThreadStart(Activity_DoWork));
_thred.Start();
}
Activity_DoWork()
{
/*Do some things...
}
This method is correct working with ASP pages. The ASP page with BackgroundWorker will not start while BackgroundWorker will finish.
5 years later, but problems the same… If you want to perform fire-and-forget operations from your application and forget about all difficulties related to background job processing in ASP.NET applications, you can use http://hangfire.io.
It does not loose your jobs on recycling process, because it uses persistent storage to keep information about background jobs.
It automatically retries your background jobs that were aborted or failed due to transient exception (SMTP Server connectivity errors).
It allows you to easily debug background jobs through the integrated web interface.
It is very easy to install/configure/use HangFire.
There is also tutorial Sending Mail in Background with ASP.NET MVC for using HangFire with Postal.

Resources