asynch process in asp.net - asp.net

I am migrating an app written on asp.net 1.1. There is a process which can take 5 minutes on one page, processing data in SQL, and letting the user know when it's complete.
To get around the HTTP page timeout, the process runs asynchronously and the page refreshes every 5 seconds checking for completion. It's very simple. Here is the problem: I use a session variable as a semaphore to signal process completion.
This is not working now as I cannot read the semaphore set in the asynch process. The asynch process can read the session from the calling routine, but cannot write back.
First, is there a way to get the asynch process to write to a session variable which can be read by another process? This probably is not the best approach today, but getting the app working is my biggest priority.
Second, if I rewrite it, what approach should be used? This is an asp web app. Not MVC.

use callback technologie it allow you to query an operation server side from your client and get a return from server so no session to manage any more:
http://msdn.microsoft.com/en-us/library/ms178210(v=vs.80).aspx

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 batch process

I have been investigating an issue for a while now-any help would be great.
Simply put I have to run an asp.net process in the background.So currently when I postback, it does processing for a few minutes. I tried the standard approach of forking another process in the postback for the batch process and returning .However my batch process uses a ASP.NET control(specifically ReportViewer) for processing.This implies it cannot run in another thread. How do we solve this problem.Does this mean reports cannot be generated in Batch mode?.
As a compromise I am happy if the postback waits for the job to finish.But I want to display status in the client.For this while postback is on I tried to make ajax calls to server to get status.But the problem is that for a session you can only use a single thread(UI). So when I make a ajax call it waits for the postback to finish and release the thread.
I am at my wits end as this is a simple and obvious requirement
thanks
My first thoughts.
Can you spin off a back ground thread that and pass the HTTPContext to it? Then you could send responses to the client, while the primary thread is busy?
But this artcle Asynchronous Pages in ASP.NET 2.0 may have a better pattern for you.

Asynchronous invocation in a ASP.NET application

I'm not talking about asynchronous pages or asynchronous handlers, I just want to know if I should be afraid of any side effect when I invoke an asynchronous method that will end after the page is finished rendering.
Example given: Each time that a user do login, I have to launch a heavy and time consuming SQL operation, but the user doesn't need to know the result of that operation, so I can execute the query using BeginExecuteNonQuery without pass any callback, and finish rendering the page.
My concern is, what happen if the HTTP call ends (because the page is served) and whatever I've executed asynchronously is already running? is ASP.NET or IIS going to cut, destroy, void anything?
Cheers.
That operation will run, even when the request has finished. However, please note that the ASP.NET host aggressively kills threads. When IIS has any reason for unloading or recycling the AppDomain, your background thread will be killed. Unloading happens in several situations. For instance when no new requests have come in for a certain period of time. Or when too many exceptions are fired from the application within a certain period of time. Or when the memory pressure gets too high.
If you need the guarantee, that the operation will finish, I think there are three things you can do:
Speed up the operation so that it can run synchronously, or
Move that that heavy operation to a Windows Service and let that execute it, or
You can hook onto the HostingEnvironment.RegisterObject method (as Phill Haack explains here) (demands full trust) to prevent the AppDomain to go down while that thread is running.
If you have a callback registered, the process will comeback to notify the callback otherwise it will still complete the job. AFAIK - neither ASP.NET or IIS will cut/destroy or void anything as the execution was already ordered and it has to complete.

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.

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