Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.Net, How do I run code after sending page

In ASP.Net, I want to run some code (logging, other cleanup) after the page has already been sent to the user. I don't want this code to interfere with the amount of time it takes the client to receive a response. I tried placing this code in the OnUnload part of the page, but through testing (using breakpoints, or busy waiting loops) the client does not actually display the page until the code in the OnUnload is finished executing. Even though the response object is no longer available at this point, and therefore I would assume that the buffered response has been sent to the client, the client still does not display the page until the OnUnload is finished executing. The only way that seems to work at the moment is to start a new thread to do the work, and allow the OnUnload to finish immediately. However, I don't know if this is safe or not. Will the server kill the thread if it executes too long after the page is already sent out? Is there a more correct way to accomplish this?

like image 306
Kibbee Avatar asked Sep 06 '25 03:09

Kibbee


2 Answers

Kibbee,

Try overriding the Page.Render method and flushing the response like so:

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
    MyBase.Render(writer)

    Response.Flush() ' Sends all buffered output to the client

    ' Run some code after user gets their content
End Sub

I think at this point the response still isn't complete, but the user will get what the page has rendered before you finish running that final code.

HTH,

Mike

like image 86
mclark1129 Avatar answered Sep 07 '25 21:09

mclark1129


Unload is the last part of the ASP.NET page life cycle. See link below:

http://msdn.microsoft.com/en-us/library/ms178472.aspx

Is this something you could do with javascript or AJAX?

like image 25
Abe Miessler Avatar answered Sep 07 '25 20:09

Abe Miessler