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

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

Related

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 process ajax request during batch process

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.

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.

Asynchronous web service call in ASP.NET/C#

We have an application that hits a web service successfully, and the data returned updates our DB. What I'm trying to do is allow the user to continue using other parts of our web app while the web service processes their request and returns the necessary data.
Is this asynchronous processing? I've seen some console app samples on the msdn site, but considering this is a web form using a browser I'm not sure those samples apply. What if the user closes the browser window mid request? Currently we're using the Message Queue which "waits" for the web service to respond then handles the DB update, but we'd really like to get rid of that.
I'm (obviously) new to async requests and could use some help figuring this out. Does anyone have some code samples or pertinent articles I could check out?
Yes, what you're describing is async processing.
The best solution depends to some degree on the nature of the web services call and how you want to handle the results. A few tips that might help:
One approach is to send a request from the initial web request to a background thread. This works best if your users don't need to see the results of the call as soon as it completes.
Another approach is to have your server-side code make an async web services call. This is the way to go if your users do need to see the results. The advantage of an async call on the server side is that it doesn't tie up an ASP.NET worker thread waiting for results (which can seriously impair scalability)
Your server-side code can be structured either as a web page (*.aspx) or a WCF service, depending on what you want to have it return. Both forms support async.
From the client, you can use an async XMLHTTP request (Ajax). That way, you will receive a notification event when the call completes.
Another approach for long-running tasks is to write them to a persistent queue using Service Broker. This works best for things that you'd like users to be able to start and then walk away from and see the results later, with an assurance that the task will be completed.
In case it helps, I cover each of these techniques in detail in my book, along with code examples: Ultra-Fast ASP.NET.
If you're not blocking for a method return you're doing asychronous processing. Have a look at Dino Esposito's article on using AJAX for server task checking.
You can perform asynchronous web service calls using both Web Service Enhancements (WSE) and Windows Communication Foundation (WCF) in your C# code. WSE is discontinued, so its use is not recommended. Generically speaking, if you were to terminate program execution in the middle of an asynchronous call before the response returned, nothing bad would happen; the client would simply not process the result, but the web service would still be able to perform its processing to completion.
If your client web application is responsible for updating the DB, then without anything else in your client code, quitting in the middle of an asynchronous operation would mean that the DB was not updated. However, you could add some code to your client application that prevented the browser from quitting entirely while it is waiting for an asynchronous response while preventing new web service calls from being run after Close is called (using Javascript).
You have 2 distinct communications here: (1) from web browser to web application and (2) from web application to web service.
diagram http://img697.imageshack.us/img697/6713/diagramo.png
There is no point of making (2) asynchronous: you still would have to wait for web service to finish processing request. If you end HTTP request from browser to web application the client would have no clue what the result of request was.
It is much better to make asynchronous request from web browser to your web application. Ajax is ideal for that. In fact, that's what it was created for. Here's couple of links to get you started:
jQuery Ajax
ASP.NET AJAX

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