473,748 Members | 5,232 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems with Asynch Processing in ASP.Net

This is my first attempt as asynchronous processing. I have created a
small test app as proof of concept, but I am having one proglem. In
the example (code listed below), my callback routine has two problems:

1. It runs TWICE; and
2. While it seems to update the web page controls, the results never
show up on the page.

I am using delegates per a couple of examples I found on MSDN and
elsewhere.

What I'm trying to accomplish is to spawn an asynchronous routine from
the page. When the routine is complete and the callback routine
executes, it should update the screen to let the user know it's done.

Any help would be greatly appreciated. My code is listed below.

Sincerely,
Glen Wolinsky

--------------------------
Numbers 6:24-26
--------------------------
-------------------------------------------------------------------------------------------------------------

Imports System.Threadin g

Public Class AsynchTest1

Inherits System.Web.UI.P age

Protected WithEvents btnGo As System.Web.UI.W ebControls.Butt on
Public Delegate Function TestDelegate() As String
Dim intTemp As Integer

------Page Load
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load

End Sub

------Button to start process
Private Sub btnGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles btnGo.Click
Session("StartP roc") = Today.Now

Dim TestDlgt As TestDelegate = New TestDelegate(Ad dressOf
TestRoutine)

Dim ar As IAsyncResult = TestDlgt.BeginI nvoke(New
AsyncCallback(A ddressOf TestComplete), _
Nothing)

lblStatus.Text = "Procedure started..."

End Sub

-------Asynchronous Routine
Private Function TestRoutine() As String
Dim start As DateTime

SyncLock Session.SyncRoo t
start = Session("StartP roc")
End SyncLock

Do While (Date.Now.Ticks - start.Ticks) < 100000000
'Process this loop for a few seconds
Loop

Return "The asynchronous process is complete"
End Function
------Completion callback routine
Private Sub TestComplete(By Val ar As IAsyncResult)
Dim ad As TestDelegate = CType(ar.AsyncS tate, TestDelegate)

lblStatus.Text = ad.EndInvoke(ar )
lblStatus.ForeC olor = Color.Red

End Sub

End Class
Nov 18 '05 #1
11 1764
Maybe you need to use Threading. I've never done any async stuff, but I've
used Threading with GREAT success.

Take a look at this and see if this helps ya:
http://www.fawcette.com/vsm/2002_11/...tures/chester/
http://www.sitepoint.com/article/1017/3

Michael
"Glen Wolinsky" <gw*******@mill ermartin.com> wrote in message
news:bb******** *************** ***@posting.goo gle.com...
This is my first attempt as asynchronous processing. I have created a
small test app as proof of concept, but I am having one proglem. In
the example (code listed below), my callback routine has two problems:

1. It runs TWICE; and
2. While it seems to update the web page controls, the results never
show up on the page.

I am using delegates per a couple of examples I found on MSDN and
elsewhere.

What I'm trying to accomplish is to spawn an asynchronous routine from
the page. When the routine is complete and the callback routine
executes, it should update the screen to let the user know it's done.

Any help would be greatly appreciated. My code is listed below.

Sincerely,
Glen Wolinsky

--------------------------
Numbers 6:24-26
--------------------------
-------------------------------------------------------------------------- -----------------------------------
Imports System.Threadin g

Public Class AsynchTest1

Inherits System.Web.UI.P age

Protected WithEvents btnGo As System.Web.UI.W ebControls.Butt on
Public Delegate Function TestDelegate() As String
Dim intTemp As Integer

------Page Load
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load

End Sub

------Button to start process
Private Sub btnGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles btnGo.Click
Session("StartP roc") = Today.Now

Dim TestDlgt As TestDelegate = New TestDelegate(Ad dressOf
TestRoutine)

Dim ar As IAsyncResult = TestDlgt.BeginI nvoke(New
AsyncCallback(A ddressOf TestComplete), _
Nothing)

lblStatus.Text = "Procedure started..."

End Sub

-------Asynchronous Routine
Private Function TestRoutine() As String
Dim start As DateTime

SyncLock Session.SyncRoo t
start = Session("StartP roc")
End SyncLock

Do While (Date.Now.Ticks - start.Ticks) < 100000000
'Process this loop for a few seconds
Loop

Return "The asynchronous process is complete"
End Function
------Completion callback routine
Private Sub TestComplete(By Val ar As IAsyncResult)
Dim ad As TestDelegate = CType(ar.AsyncS tate, TestDelegate)

lblStatus.Text = ad.EndInvoke(ar )
lblStatus.ForeC olor = Color.Red

End Sub

End Class

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.564 / Virus Database: 356 - Release Date: 1/19/2004
Nov 18 '05 #2
your missing the concept of how page processing happens.
browser requests pages (or post on click) -->

server builds page
oninint
onload
onclick
onprerender
onrender
<-- page sent back

browser renders page

you are starting a async proc during onclick, but you have no delay (say at
prerender) on the page to wait for the async process to complete. so the
page html is sent back to the browser before it completes. it can change
class variables and controls, but will have no impact, because the response
has already been sent.

if you want the page to render, then be updated after the async is done, the
browser needs to poll for the results. have the async routine write its
results to session, then using the refresh meta tag, postback every couple
seconds to see if it has completed. a little javascript and a hidden frame
can be handy here.

-- bruce (sqlwork.com)

"Glen Wolinsky" <gw*******@mill ermartin.com> wrote in message
news:bb******** *************** ***@posting.goo gle.com...
This is my first attempt as asynchronous processing. I have created a
small test app as proof of concept, but I am having one proglem. In
the example (code listed below), my callback routine has two problems:

1. It runs TWICE; and
2. While it seems to update the web page controls, the results never
show up on the page.

I am using delegates per a couple of examples I found on MSDN and
elsewhere.

What I'm trying to accomplish is to spawn an asynchronous routine from
the page. When the routine is complete and the callback routine
executes, it should update the screen to let the user know it's done.

Any help would be greatly appreciated. My code is listed below.

Sincerely,
Glen Wolinsky

--------------------------
Numbers 6:24-26
--------------------------
-------------------------------------------------------------------------- -----------------------------------
Imports System.Threadin g

Public Class AsynchTest1

Inherits System.Web.UI.P age

Protected WithEvents btnGo As System.Web.UI.W ebControls.Butt on
Public Delegate Function TestDelegate() As String
Dim intTemp As Integer

------Page Load
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load

End Sub

------Button to start process
Private Sub btnGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles btnGo.Click
Session("StartP roc") = Today.Now

Dim TestDlgt As TestDelegate = New TestDelegate(Ad dressOf
TestRoutine)

Dim ar As IAsyncResult = TestDlgt.BeginI nvoke(New
AsyncCallback(A ddressOf TestComplete), _
Nothing)

lblStatus.Text = "Procedure started..."

End Sub

-------Asynchronous Routine
Private Function TestRoutine() As String
Dim start As DateTime

SyncLock Session.SyncRoo t
start = Session("StartP roc")
End SyncLock

Do While (Date.Now.Ticks - start.Ticks) < 100000000
'Process this loop for a few seconds
Loop

Return "The asynchronous process is complete"
End Function
------Completion callback routine
Private Sub TestComplete(By Val ar As IAsyncResult)
Dim ad As TestDelegate = CType(ar.AsyncS tate, TestDelegate)

lblStatus.Text = ad.EndInvoke(ar )
lblStatus.ForeC olor = Color.Red

End Sub

End Class

Nov 18 '05 #3
Michael,

Thanks for the reply. I looked at threading and got some samples
working well using session variables for status info.

However, after reading several articles on this type of thing, the
consensus seemed to be that asynch processing was better and more
scaleable than threading.

I need this feature for just a handful (2-5) users who do large searches
on our data warehouse. The search runs fine but the exporting of that
data to other systems or to an excel spreadsheet causes the browser to
time out.

I got one asynch test working, but I still had to use session variables
to check status.

Should I be using asynch to let asp.net manage the thread pool for me?
Anyone who can advise me on the pro's and con's of each would be greatly
appreciated.

Sincerely,
Glen Wolinsky
--------------------------
Numbers 6:24-26
--------------------------

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 18 '05 #4
Bruce,

Thanks for your response. I have managed to get that exact scenario
working in both threading and asynch processing. My next question is
this: Which one is best to use? They both seem to do the same thing
except that asynch has a few extra "bells and whistles" and uses the
thread pool.

Thanks,
Glen Wolinsky

--------------------------
Numbers 6:24-26
--------------------------

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 18 '05 #5
Hi Glen,
Thanks for posting in the community! My name is Steven, and I'll be
assisting you on this issue.
From your description, you'd like to implement a asynchronous processing to
register a call back method when page is being generated and loading so as
to use the call back method to update some certain server controls when a
certain longtime operation is completed. However you found it didn't work
as you expected when you run the test page, yes?
If there is anything I misunderstood, please feel free to let me know.

As for this problem, here is my suggestion on it:
The ASP.NET web application is one kind of the page based B/S mode
application. The application consist of two parts: the severside and the
client side. Generally, the client side user request a certain page on the
server, the then the server side use the Dynamical document tech such as
ASP.NET to create the page (which start the server page's life cycle , page
init , load .....). And all the serverside code all being executed during
the lifecyle, after the page is generated and ouput(render) to client side.
The page's server life cycle ended and there is no relation between the
client page and the memory page object on the serverside(in fact, it'll be
cleared in the server side memory). And in the next time the same page
requested, another page instance will be generated in serverside memory. In
other words, no persistant connection is remained between the client and
the server, this is also the characteristic of the HTTP based compute
mode-------stateless. That's quite different from the mode in Winform
application , in which all the object instance are all in memory during the
runtime and can be retrieve and maintain until the program end. So as for
your situation, the asynthronized call back method is registed in the
page's life cycle, at that time , the page and its sub object instances are
all avaliable on the serverside. However, when the certain task finished,
just when the callback method is called, the page may have already been
output to the client side, so it's unable to retrieve the page and modify
it's members. Also, even if you get the object, there is not relation with
the instance and the client side's page. Do you think so? For more info
about the ASP.NET page model, you may view the following reference in MSDN:
#The ASP.NET Page Object Model
http://msdn.microsoft.com/library/en...eobjectmodel.a
sp?frame=true

In addition, as for your requirement, I think we could use other means to
implement it in B/S mode application. For example, we could let the page be
send back to client and continue the operation on the serverside, and the
page in the client side constantly post back to server side to check
whether the operation is completed, if so, then do the later operations.
And here is some tech articles which focus on such asynchronous pattern in
web application:

#DESIGN PATTERNS: Asynchronous Wait State Pattern in ASP.NET
http://msdn.microsoft.com/msdnmag/is...s/default.aspx
http://www.aspnetpro.com/NewsletterA..._l/asp200308bm
_l.asp

Please check out to see whether they're helpful. In the meantime, if you
have any further questions, please feel free to post here.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Nov 18 '05 #6
Steven,

Thanks for all of the information. You have confirmed everything I have
read and learned on this subject in the past 5 days. Now, I have
another question:

Scenario:

1. A user selects a long-running action (process).

2. I take the user to a "wait" page. The wait page actually spawns the
thread (on my own without using async processing) and keeps posting back
to monitor the process via session variables.

3. If I save a reference to the thread object in session, can I abort
the thread using code in my page?

What I'm trying to accomplish is that if the user exit's the page
(including closing the browser window) that the thread(process) will be
aborted.

Any thoughts, suggestions or other miscellaneous ideas? ;o)

Thanks,
Glen Wolinsky

--------------------------
Numbers 6:24-26
--------------------------

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 18 '05 #7
Hi Glen,
Thanks for your response. As for the questions you mentioned in the reply,
here is my suggestions:
1. You'd like to run a work thread on the serverside and store the thread
object in session. And you'd like to retrieve back and do operations on it
(such as abort or stop). This is ok, you can first create the thread and
start it at begining. For example:
ThreadStart ts = new ThreadStart(DoW ork);
Thread thd = new Thread(ts);
thd.Start();
Session["thread"] = thd;

Then, when in one of the page's post back event, you could retrieve the
thread object and suspend or abort it, for instance:
private void btnAbort_Click( object sender, System.EventArg s e)
{
try
{
Thread thd = (Thread)Session["thread"];
thd.Abort();
}
catch(Exception ex)
{
Response.Write( "<br>" + ex.Message);
}
}

2. You'd like to abort such a serverside background thread when user exit
site or close browser window?
As for this problem, I think it is easy to accomplish in case user
explicitly exit the page(such as click a button), you can abort the thread
as I mentioned above. However, the difficulty is when the user just close
the browser,. As we know that if the browser is closed, no relation between
the client and server exist. , so we need to let the serverside know that
the user has left, and here is two general means to accomplish this:
1). use the client script to capture the page's "onunload" event and then
post back to certain page to do the cleanup operations. For example, in the
page set such unload handler
-------------------------
..............
<script language="javas cript">
function CloseHandler()
{
if(window.close d)
{
window.open("Cl eanUp.aspx");
}
}
</script>
</HEAD>
<body onunload="Close Handler()" >
............... ....

In the CleanUp.aspx we add the clean up operations such as abort the
thread or release other resources.
# this means has a problem: when you refresh the page(not close it), the
"unload" event will also be fired!

2). Use the "Session_En d" event of the Global object on serverside. Since
when the Session is ended(user logout) or Timeout(user long time no visit
the application). The Session_End event will be fired, we can also do the
clean up operations in it.

Please check out the above suggestions. If you have any questions on them,
please feel free to let me know.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #8
Steven,

Thanks for all your time. You've been very helpful. One more question:

if I raise an event in a threaded process, can my "Wait.aspx" page
detect that event?

Thanks,
Glen

--------------------------
Numbers 6:24-26
--------------------------

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 18 '05 #9
Hi Glen,
Thanks for your prompt response. As for the question in your reply:
---------------
if I raise an event in a threaded process, can my "Wait.aspx" page
detect that event?
---------------

here is my suggestions:
As I 've mentioned in the former reply. The certain threaded process is
running on the serverside. And the wait.aspx will be rendered out and send
to the clientside and the page's life cycle is only during the time it is
constructed and operated on the serverside(it's a very short time). So it
impossible to use the Dotnet event and callback mechanism to let a page be
sense of a serverside throwed event. I suggest that you use the below
approach:
1.Let the wait.aspx constantly post back to the server side to check a
certain Session object 's value. The value is just a flat to indicate
whether the certain threaded process has finished.

2.In the threaded process , when it has finished, set the certain Session
object 's value as the Finish state's value so that the next the wait page
post back , it can detect the change.

How do you think of the above means? If you still feel anything unclear on
it, please feel free to let me know.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Nov 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1870
by: Mr. Mountain | last post by:
In the following code I simulate work being done on different threads by sleeping a couple methods for about 40 ms. However, some of these methods that should finish in about 40 -80 ms take as long as 2300 ms to complete. This is fairly rare, but the test code below will definitely show it. Somehow, I must not have my design right. The idea of this code is that I do two different types of processing ( 1-starting and 2-ending) based on...
2
1560
by: ghost | last post by:
As the Subject indicates I have written a web page that makes use of several web service calls. Some of the web service calls are very fast so they called synchronously. Some web service calls are longer running so I call them asynch so that they can all run concurrently. The user base for the application that I am creating demands the partial response of the faster calls and a gradual update of their web page info from the balance of...
16
2537
by: pamelafluente | last post by:
I am still working with no success on that client/server problem. I need your help. I will submit simplified versions of my problem so we can see clearly what is going on. My model: A client uses IE to talk with a server. The user on the client (IE) sees an ASP net page containing a TextBox. He can write some text in this text box and push a submit button.
2
1096
by: Techno_Dex | last post by:
What is the correct way to debug a WS which makes it's call Asynch?
1
2640
by: Sean | last post by:
I am looking at using delegates to perform an asynchronous call. There will be a callback invoked at the end of the call. The client thread will wait on the WaitHandle from IAsyncResult (which is really a AsyncResult). My question is, when exactly is this WaitHandle signalled - is it: -when the asynchronous call finishes OR -when EndInvoke() is called (by the callback)
4
1872
by: EM_J | last post by:
I am implementing this interface in one of my pages. The RaiseCallbackEvent method runs a task for about 3 seconds. I've noticed when I am on that page and click a tab to navigate to another page, it may take up to 3 seconds to redirect. If I decrease the time to 500 ms, the redirect happens much faster. So it seems like this asynch task is not really asynch, since the redirect is waiting for it to complete. Am I misunderstanding...
0
1031
by: simonZ | last post by:
I'm using Asynch data tasks to create my data readers and after a couple of executions, the page doesn't render any more. There is always timeoutAsynchOperation. First time when this happens, in background, all the jobe in sql is done only the data is not thrown back. I guess: when user disconects from the pool, the asynch operation executes the procedure on sql server and when it is finished, it can't connect the user back to the pool....
0
1151
by: =?Utf-8?B?aGVyYmVydA==?= | last post by:
I have a messaging API which creates notification responses for multiple requests ( interfacing a device on SerialPort class). So I created a layer following the event-based asynchronous pattern. The request is sent to RS-232 using MethodNameAsynch() and the response creates an event. There are multiple methodnameAsynch() calls and events, each of them can be called multiple times using userState objects. Now I want to wrap this layer...
0
1370
by: Patino | last post by:
I have a particular WS consumer application (Windows app) that was not able to read an error from the WS app because it was calling a method asynch. The client app just hangs there. But once I switched the call to a synch, the client app got the error message and displayed it nicely to the user. In this client app. the user does not have to do anything while waiting for results to come back from the web, so it makes sense to call the...
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9548
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9325
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.