 |
|
 |
Hi Brandon
I know this is an old post but this is exactly what I was looking for, a simple and concise sample on how to do threading in ASPX.
Thank you!!
5 out 5!
Well done!
Regards
Taner
modified on Saturday, April 24, 2010 8:15 AM
|
|
|
|
 |
|
 |
The sample code did not work for me because the session object was not accessible in the thread. Perhaps this behavior has changed since the article was written.
MSDN has a good example that shows how to pass a parameter into a new thread. It then uses the Thread.Join() method to find out when the thread has finished.
http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx
Here is my ASP.NET version of the MSDN sample in C#:
<![CDATA[<%@ Page Language="C#" %>]]>
<![CDATA[<%@ Import Namespace="System.Threading" %>]]>
<script runat="server">
public void StartProcess_Click(object sender, EventArgs e)
{
Response.Buffer = false;
Response.Write("Main thread: Start a second thread at: " + DateTime.Now.ToLongTimeString() + " ");
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. C# simplifies the creation of this delegate.
//Thread t = new Thread(new ThreadStart(DoWork.Work));
Thread newThread = new Thread(SecondThread.Work);
// Start ThreadProc. Note that on a uniprocessor, the new
// thread does not get any processor time until the main thread
// is preempted or yields. Uncomment the Thread.Sleep that
// follows t.Start() to see the difference.
newThread.Start(tbParameter.Text);
Response.Write("Main thread: Call Join() to wait until ThreadProc ends.
");
newThread.Join();
Response.Write("Main thread: ThreadProc.Join has returned at: " + DateTime.Now.ToLongTimeString() + " ");
}
class SecondThread
{
public static void Work(object objseconds)
{
int seconds = Convert.ToInt32(objseconds);
Thread.Sleep(seconds * 1000);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
Seconds for thread to run:
<asp:textbox id="tbParameter" runat="server" xmlns:asp="#unknown">
<asp:button id="btnStartThread" runat="server" text="Start" xmlns:asp="#unknown">
OnClick="StartProcess_Click" />
</form>
</body>
</html>
|
|
|
|
 |
|
 |
A workaround would be to use a database table with a control record/row that contains your own variables/flags.
But it worked for me...
Regards
Taner
|
|
|
|
 |
|
 |
the procedue StartLongProcess() would blow up at the line
Session[PROCESS_NAME] = true;
You can not access Session from the working thread. Have you tested your code at all????
|
|
|
|
 |
|
 |
It worked for me but I am on VS2008 using VB.NET and the "System.Threading" namespace, there is no "System.Web.Threading" in VB.NET on VS 2008...
Regards
Taner
|
|
|
|
 |
|
 |
Thanks Brandon,for this nice well written article.It really helped me a lot.
|
|
|
|
 |
|
 |
Asynched thread? I would like to be able to send information possibly saying something like "message x of y" sent. Should I have an event handler that can be raised somehow across threads? Or is there a way to pass back an argument in this model.
This is exactly what I need except I'm trying to understand how to get a message back...
|
|
|
|
 |
|
 |
Maybe you can communicate with SessionVars?!
|
|
|
|
 |
|
 |
Hi!
I allways used threads this way with several feed-backs but this time
i'm generating an file as output with no more news, and everything is
is allright i my computer.
But, when a copy my web-application to my
a friend computer, the file did not even appear and no exception was
throwned as well for the thread creation and start run.
Is like the thread never was there!
My, latested ideia about this was that the thread on my friend computer
dies when the requested page is responsed to the browser; while on my computer
it stays alive...
My question is: Does any one know what conditions are to config so the thread
is there and alive after page response?
|
|
|
|
 |
|
 |
This example is exactly what I need, except I would rather it redirect
to a page that says "your request has been submitted, check back later". So, I really don't need to return anything to the user.... the LongProcess can just tidy up itself then terminate. What can I change/eliminate to do that? Thanks much.
-- modified at 10:55 Wednesday 23rd August, 2006
|
|
|
|
 |
|
 |
Thanks for the article it's saved me loads of time.
The only problem I have is that I keep intermitantly losing the session so causing a null reference error.
Could it be that both threads are trying to access the session at the same time? do I need to lock the session within each thread.
Any help would be greatly appreciated
|
|
|
|
 |
|
 |
For some reason or another when the process is complete all my fields that I entered values for and sent to the server to return data are empty. Basicilly what I am saying is that I have a form. When the user clicks on the submit button it starts the thread and redirects to the processingMessage page but when it returns to the page that I submited the form fields are empty. How can I keep from lossing the data entered by the user on Redirect.
Jesus
|
|
|
|
 |
|
 |
GRRR. Did you figure this out yet, let me know, I'm having the same problem.
|
|
|
|
 |
|
 |
Hi,
Has anyone sorted this out yet? I am running into the same problem and don't know how to get around it. When I go back to the original page the IsPostBack is false.
|
|
|
|
 |
|
 |
When form is submitted, and you start a long running process, you may as well store submitted values in the database.
Of course ViewState is lost on refresh, because Refresh does not result in a PostBack.
Another alternative is to have Query parameters in your URL like http://somesite.com/default.aspx?param1=value1
Alexander
|
|
|
|
 |
|
 |
Ok here is my problem: The script works fine, but when i enter in the seconds the waiting is not the same time that I enter. Lets say that I put in 5 ( 5*1000), well instead, it comes out to be like 5000(5*10000000)seconds. I'm not sure if its the initilization thread or if I'm using the wrong thread. Here is my code:
SubmitProcessing.aspx
Sub SubmitButton_OnClick(Byval sender as Object, ByVal e as EventArgs)
Session(PROCCESS_NAME) = FALSE
'Create and initialize new thread with the address of the StartLongProcess function
Dim thread as Thread = New Thread(New ThreadStart(AddressOf StartLongProcess))
'Start Thread
thread.start()
'Pass redirect page and session var name to the process wait(interum) page
Response.Redirect("AsynchronousProcessing_A_Example.aspx?redirectPage=SubmitLongProcess.aspx&ProcessSessionName=" + PROCCESS_NAME+"&ProcessTime="+txtProcessLength.text)
End Sub
Sub StartLongProcess()
'Initialize Session variable
'Session(PROCCESS_NAME) = false
'Replate the following line of ocde with your long process
response.Write("Test")
response.End()
Thread.Sleep(Convert.ToInt32(txtProcessLength.text) * 1000)
'Set session variable equal to true when process complets
Session(PROCCESS_NAME)=true
Cache.Insert(Session.SessionID + PROCCESS_NAME,"done")
End Sub
ProcessingSubmit.aspx
Sub Page_Load(ByVal sender as Object, ByVal e as EventArgs)
Dim redirectPage as String = Request.QueryString("redirectPage")
Dim processSessionName as String = Request.QueryString("ProcessSessionName")
Dim ProcessTime as String = Request.QueryString("ProcessTime")
session("ProcessTime") = ProcessTime
'session("ProcessTime") = Request.QueryString("ProcessTime")
if(session("ProcessTime") = NOTHING) then
response.Write("ProcessTime is null")
StatusMessage.text = "Process has been running for 0 seconds"
Session("ProcessTime") = 0
else
response.Write("ProcessTime is not null")
Session("ProcessTime") = Convert.ToInt32(session("ProcessTime").ToString())
StatusMessage.text = "Process has been running for " + Session("ProcessTime").ToString() + " seconds"
end if
if Cache(Session.SessionID + processSessionName) = "done" then
Cache.Remove(Session.SessionID + processSessionName)
Session("ProcessTime") = nothing
Response.Redirect(redirectPage)
end if
'if Session(processSessionName)= true then
'Session(processSessionName) = " "
'Session("ProcessTime") = " "
'Response.Redirect(redirectPage)
'End if
End Sub
|
|
|
|
 |
|
 |
Hello,
I'm not exactly sure what could be causing this problem. Have you attempted to step through the code putting a breakpoint inside of the new thread? Also, have you tried to hard code the sleep parameter?
Thread.Sleep(5000)
Let me know what happens when you run these two tests.
Thanks,
Brandon
|
|
|
|
 |
|
 |
Looks very good and simple, your example runs but when I convert to vb, I have this
Dim oThread As New Thread(New ThreadStart(AddressOf LookupEmail))
oThread.Start()
Response.Redirect("process.aspx?pg=0")
end sub
Private Sub LookupEmail()
Session.Item(cstPROCESS_ASYNC) = False
Thread.CurrentThread.Sleep(10000)
Session.Item(cstPROCESS_ASYNC) = True
End Sub
Unfortunately, at this line Session.item(cstPROCESS_ASYNC), I get this error:
An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in Unknown Module.
Additional information: Het type System.Web.HttpException in assembly System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a is niet als serialiseerbaar gemarkeerd.
When I add watches to the var cstPROCESS_ASYNC and the Thread.Sleep(10000) everything looks normal, no exceptions occur...
What can I do to make this work, because it is the best piece of code that I have found to make async tasks...
Philippe
|
|
|
|
 |
|
 |
Hi Philippe,
Try moving Session.Item(cstPROCESS_ASYNC) = False before the following line of code:Dim oThread As New Thread(New ThreadStart(AddressOf LookupEmail))
Let me know what happens.
Brandon
|
|
|
|
 |
|
 |
After I submitted the problem, I tried it and it worked...
but sometimes I got the error when I started the application and sometimes not...
I have rebooted the computer and now it seems to work, but I will remember your tip for the future
should any problem occur, I will post it here
Thanks for the help ! This article is really what I needed for some time
Philippe
|
|
|
|
 |
|
 |
It is very strange, sometimes when I start up the app, it uses the processing page 3 times.
Action one, redirect to process, start new thread
back tot aspx page, trigger another lookup action
Action two, redirect to process, start new thread
it is always the second time that I start a new thread, that I get the error...
it always is on my development machine, I haven't tested it yet on the deployment server...
Philippe
|
|
|
|
 |
|
 |
Hey,
Browsing through the internet, some articles say that it is because the new thread that I created in the second page, conflicts with the thread that I created in the first page. This makes sence to me, because it is always the second or third time that the studio gives this error, never the first time...
I'l keep on searching...
Philippe-
|
|
|
|
 |
|
 |
Hi Philippe,
Are you saying that you're starting another new thread in the Processing page? I guess I'm a little confused at what you're attempting to do. You shouldn't leave the Processing page until the thread on the submit page is complete. The Session variable after your long process should inform the processing page that the thread is complete. Therefore, you would only one new thread at a time.
I hope this makes sense. Thanks!
Brandon
|
|
|
|
 |
|
 |
Sorry, but I think I explained it wrong. I will go through the steps
Page1: I'm going to verify an email adres with a webservice, therefore I start a new thread, contacting the webservice and I redirect to the processpage
Thread finished, processpage redirects back to page 1 where I get the results from a session object
User goes to the next step
Page2: Recover password feature via webservice, I start new thread to contact the service, redirect to processpage
thread finished, processpage redirects back to page 2 where I get ....
Page3: Logon, get userinfo from webservice, again, contact webservice via new thread etc etc
The first time that I make a new thread it always works, but the second or third time it can fail, very annoying...
Does the thread when finished, stops and removes itself? Shouldn't I somewhere say thread.stop(maybe with an ID) ?
I hope I wrote it correct, do you have any idea what i could do about it?
Thanks in advance
Philippe
|
|
|
|
 |
|
 |
Brandon,
The problems keeps coming up when you try to call the wait page more then once in a session.
So I will try something else, this solutions seemed so simple, but unfortunately...
regards Philippe
|
|
|
|
 |