Asynchronous Page?

How can I make this page utilize asynchronous processing?

I am thinking the the commented sections are the ones that should be run asynchronously...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim tmpString As New StringBuilder, CatID As Long, Parent = False
        Dim StringToQuery As String = String.Empty
        Try
            If Not (IsNothing(HttpContext.Current.Request.QueryString)) Then
                StringToQuery = HttpContext.Current.Request.QueryString(0).ToString()
            End If
            Dim QryArr() As String = StringToQuery.Split("/")
            '---------------------------------------
            'Should be part of the async processes
            '---------------------------------------
            If UBound(QryArr) - 1 = 1 Then
                CatID = LookUps.GetCategoryID(QryArr(1), LookUps.GetCategoryID(QryArr(0)))
                tmpString.Append(ShowBreadCrumbs(CatID))
            ElseIf UBound(QryArr) - 1 = 0 Then
                Parent = True
                CatID = LookUps.GetCategoryID(QryArr(0))
                tmpString.Append(ShowBreadCrumbs(CatID))
            End If
            '---------------------------------------
            '---------------------------------------
        Catch ex As Exception
        End Try
        Dim objCat As New TurboKits.Parts
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = Parent
                '---------------------------------------
                'These Should be asynchronous processes
                '---------------------------------------
                tmpString.Append(.DisplaySubCategories())
                tmpString.Append(.DisplayCategoryParts())
                tmpString.Append(.DisplayCategoryDescription())
                '---------------------------------------
                '---------------------------------------
            Else
                tmpString.Append("<h1>Part Categories</h1>")
                tmpString.Append("<div class=""content"">Please select from our part categories on the left.</div>")
            End If
            AddSEOToPage(.MetaTitle, .MetaDescription, .MetaKeywords)
        End With
        objCat = Nothing
        Me.PartContent.InnerHtml = tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

Open in new window

LVL 25
kevp75Asked:
Who is Participating?
 
CodeCruiserCommented:
Try adding some debugging code into the DAL function which is not working. For example, instead of actual results, it should return a string containing status which is updated at different spots (for example, at the begining of sub, status is Started, then Connection Created, then Ended etc)
0
 
MajorBigDealCommented:
Sorry for not understanding but I do have a few questions that might clarify.  

To me in ASP.NET asyncronous web pages refers to a feature to help throughput by changing the way thread pools are used. But the rendering is still done at the end.  As described in this link:

http://msdn.microsoft.com/en-us/magazine/cc163725.aspx

But in some other technology, asnyc web pages involves a technique for updating webpage "automatically", similar to what we do in ajax but with even more finer grained control.  As described in this link:

http://www.theserverside.com/news/1363576/What-is-the-Asynchronous-Web-and-How-is-it-Revolutionary

Would ajax be an appropriate choice for what you are trying to do?
0
 
kevp75Author Commented:
I would say, no.  ajax wouldn't be the way to go, simply because the page is heavy enough.

I've read over that msdn article, but don't understand how I can apply it to the above code...
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
MajorBigDealCommented:
Right, I don't think that applies to you at all. So without using the word "asynchronous", what is it that you are trying to accomplish?
0
 
kevp75Author Commented:
I would like the 4 sections to fire off at the same time.  The breadcrumbs, the subcategories, the category parts, and category description.

They don't have to render all at the same time, but I do notice that they fire off syncronously
0
 
CodeCruiserCommented:
You can use Threads but it would complicate the code.
0
 
kevp75Author Commented:
ok.....  how?
0
 
MajorBigDealCommented:
Yes, you would certainly have to use multiple threads.  But even if you have them firing off at the same time, are you are planning on waiting for a response from all of them before you render the page? Or are you saying that you want to display the page and then update it as the results from the threads become available? The reason I am asking is that if you are trying to do the second case, the best way to accomplish that is by using Ajax.  
0
 
kevp75Author Commented:
i would like to do the second case, but cannot use ajax to do it.  requirement of the project...sorry
0
 
kevp75Author Commented:
here's the latest code.  I am attempting the threading method, but nothing is showing on the page now.
Partial Class Parts_Default
    Inherits System.Web.UI.Page

    Public objPC As Object, StringToQuery As String = ""
    Public QS As Object = HttpContext.Current.Request.QueryString
    Public CatID As Long, IsParent As Boolean = False
    Public objCat As New TurboKits.Parts

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        objPC = Me.PartContent
        Dim tmpString As New StringBuilder
        Try
            If Not (IsNothing(QS)) Then
                StringToQuery = QS(0).ToString()
            End If
            Dim QryArr() As String = StringToQuery.Split("/")
            If UBound(QryArr) - 1 = 1 Then
                CatID = LookUps.GetCategoryID(QryArr(1), LookUps.GetCategoryID(QryArr(0)))
                tmpString.Append(ShowBreadCrumbs(CatID))
            ElseIf UBound(QryArr) - 1 = 0 Then
                IsParent = True
                CatID = LookUps.GetCategoryID(QryArr(0))
                tmpString.Append(ShowBreadCrumbs(CatID))
            End If
            '---------------------------------------
            '---------------------------------------
        Catch ex As Exception
        End Try
        AddSEOToPage(objCat.MetaTitle, objCat.MetaDescription, objCat.MetaKeywords)
        objPC.InnerHtml = tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
        Dim objTh As New System.Threading.Thread(AddressOf AddSubCats)
        With objTh
            .Name = "SubCat"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.BelowNormal
            .Start()
        End With
        objTh = Nothing
        'AddSubCats()
        AddCatParts()
        AddCatDesc()
    End Sub

    Private Function ShowBreadCrumbs(ByVal CatID As Object) As String
        Try
            If TurboKits.Security.Required(CatID) Then
                Dim tmpString As New StringBuilder, tmpA As String = "", tmpStr As String = ""
                tmpString.Append("<span class=""breadcrumb"">")
                Dim objDb As New TurboKits.DataAccessLayer
                With objDb
                    .CommandType = TurboKits.DataAccessLayer.CmdType.StoredProcedure
                    .Query = "spBreadCrumbNav"
                    .ParamNames = New String() {"@PageID"}
                    .ParamValues = New String() {CatID}
                    .ParamDataTypes = New Integer() {TurboKits.DataAccessLayer.DataType.Int}
                    .ExecuteDataReader()
                    If .TotalRecords > 0 Then
                        Dim tmp() As String
                        tmp = .ReturnValues(0, 0)(1).Split(",")
                        For i As Long = 0 To UBound(tmp)
                            If i = UBound(tmp) Then
                                tmpString.Append(tmp(i))
                            Else
                                tmpString.Append("<a href=""/Parts/?" & HttpUtility.UrlEncode(tmp(i).Replace(" ", "_")) & "/"" title=""" & tmp(i) & """>" & tmp(i) & "</a> &raquo; ")
                            End If
                        Next
                        Erase .ReturnValues
                    Else
                        tmpString.Append(String.Empty)
                    End If
                End With
                objDb = Nothing
                tmpString.Append("</span>" & vbCrLf)
                Return tmpString.ToString()
                tmpString.Length = 0 : tmpString = Nothing
            Else
                Return ""
            End If
        Catch ex As Exception
            Dim objErr As New TurboKits.ErrorManager
            objErr.Location = "/Parts/Default.aspx - ShowBreadCrumbs"
            objErr.Stack = ex.StackTrace()
            objErr.Except = ex
            objErr.ParseError()
            objErr = Nothing
        End Try
    End Function

    Private Sub AddSEOToPage(ByVal Title As String, ByVal Description As String, ByVal Keywords As String)
        'Page Title
        Me.Page.Title = Title
        'Page Keywords
        Using objKW As New HtmlMeta()
            objKW.Name = "keywords"
            objKW.Content = Keywords
            Header.Controls.Add(objKW)
        End Using
        Me.KW.InnerHtml = "<!--" & Keywords & "-->"
        'Page Description
        Using objDesc As New HtmlMeta()
            objDesc.Name = "description"
            objDesc.Content = Description
            Header.Controls.Add(objDesc)
        End Using
    End Sub

    Private Sub AddSubCats()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplaySubCategories())
            Else
                tmpString.Append("<h1>Part Categories</h1>")
                tmpString.Append("<div class=""content"">Please select from our part categories on the left.</div>")
            End If
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Private Sub AddCatParts()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplayCategoryParts())
            End If
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Private Sub AddCatDesc()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplayCategoryDescription())
            End If
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Protected Overrides Sub Finalize()
        objCat = Nothing
        MyBase.Finalize()
    End Sub

End Class

Open in new window

0
 
CodeCruiserCommented:
Remove this line

        objTh = Nothing
0
 
kevp75Author Commented:
still nothing
0
 
kevp75Author Commented:
AddSubCats is not firing (and yes, I have verified that it does return something)
0
 
CodeCruiserCommented:
Are you generating any output from these subs that are running in separate threads?
0
 
kevp75Author Commented:
i am using the exact code above (setting the objPC control's inner html).  I have verified that the thread is running, is alive, is not a background thread.

I am going to do the same to the other 2 subs (AddCatParts, AddCatDesc), and see what they return as well



still nothing on the page
0
 
CodeCruiserCommented:
>still nothing on the page
Is that after
>I am going to do the same

or are you trying that now?
0
 
kevp75Author Commented:
3 threads.  same results...  nothing on the page
0
 
kevp75Author Commented:
sorry, I am mistaken.   with the code posted in my last code post, the only thing that is not returning anything is AddSubCats() the rest are working
0
 
kevp75Author Commented:
gets me 3 different thread id's, so I know the threads are at least being created...

but, they aren't doing anything, there is now nothing on the page (other than the design)
With objTh1
            .Name = "SubCat"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh1 = Nothing
        Dim objTh2 As New System.Threading.Thread(AddressOf AddCatParts)
        With objTh2
            .Name = "CatParts"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh2 = Nothing
        Dim objTh3 As New System.Threading.Thread(AddressOf AddCatDesc)
        With objTh3
            .Name = "CatDesc"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh3 = Nothing

Open in new window

0
 
kevp75Author Commented:
here's the full code now:

Imports System.Threading

Partial Class Parts_Default
    Inherits System.Web.UI.Page

    Public objPC As Object, StringToQuery As String = ""
    Public QS As Object = HttpContext.Current.Request.QueryString
    Public CatID As Long, IsParent As Boolean = False
    Public objCat As New TurboKits.Parts

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        objPC = Me.PartContent
        Dim tmpString As New StringBuilder
        Try
            If Not (IsNothing(QS)) Then
                StringToQuery = QS(0).ToString()
            End If
            Dim QryArr() As String = StringToQuery.Split("/")
            If UBound(QryArr) - 1 = 1 Then
                CatID = LookUps.GetCategoryID(QryArr(1), LookUps.GetCategoryID(QryArr(0)))
                tmpString.Append(ShowBreadCrumbs(CatID))
            ElseIf UBound(QryArr) - 1 = 0 Then
                IsParent = True
                CatID = LookUps.GetCategoryID(QryArr(0))
                tmpString.Append(ShowBreadCrumbs(CatID))
            End If
        Catch ex As Exception
        End Try
        objPC.InnerHtml = tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
        Dim objTh1 As New System.Threading.Thread(AddressOf AddSubCats)
        With objTh1
            .Name = "SubCat"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh1 = Nothing
        Dim objTh2 As New System.Threading.Thread(AddressOf AddCatParts)
        With objTh2
            .Name = "CatParts"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh2 = Nothing
        Dim objTh3 As New System.Threading.Thread(AddressOf AddCatDesc)
        With objTh3
            .Name = "CatDesc"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh3 = Nothing

        'AddSubCats()
        'AddCatParts()
        'AddCatDesc()
    End Sub

    Private Function ShowBreadCrumbs(ByVal CatID As Object) As String
        Try
            If TurboKits.Security.Required(CatID) Then
                Dim tmpString As New StringBuilder, tmpA As String = "", tmpStr As String = ""
                tmpString.Append("<span class=""breadcrumb"">")
                Dim objDb As New TurboKits.DataAccessLayer
                With objDb
                    .CommandType = TurboKits.DataAccessLayer.CmdType.StoredProcedure
                    .Query = "spBreadCrumbNav"
                    .ParamNames = New String() {"@PageID"}
                    .ParamValues = New String() {CatID}
                    .ParamDataTypes = New Integer() {TurboKits.DataAccessLayer.DataType.Int}
                    .ExecuteDataReader()
                    If .TotalRecords > 0 Then
                        Dim tmp() As String
                        tmp = .ReturnValues(0, 0)(1).Split(",")
                        For i As Long = 0 To UBound(tmp)
                            If i = UBound(tmp) Then
                                tmpString.Append(tmp(i))
                            Else
                                tmpString.Append("<a href=""/Parts/?" & HttpUtility.UrlEncode(tmp(i).Replace(" ", "_")) & "/"" title=""" & tmp(i) & """>" & tmp(i) & "</a> &raquo; ")
                            End If
                        Next
                        Erase .ReturnValues
                    Else
                        tmpString.Append(String.Empty)
                    End If
                End With
                objDb = Nothing
                tmpString.Append("</span>" & vbCrLf)
                Return tmpString.ToString()
                tmpString.Length = 0 : tmpString = Nothing
            Else
                Return ""
            End If
        Catch ex As Exception
            Dim objErr As New TurboKits.ErrorManager
            objErr.Location = "/Parts/Default.aspx - ShowBreadCrumbs"
            objErr.Stack = ex.StackTrace()
            objErr.Except = ex
            objErr.ParseError()
            objErr = Nothing
        End Try
    End Function

    Private Sub AddSEOToPage(ByVal Title As String, ByVal Description As String, ByVal Keywords As String)
        'Page Title
        Me.Page.Title = Title
        'Page Keywords
        Using objKW As New HtmlMeta()
            objKW.Name = "keywords"
            objKW.Content = Keywords
            Header.Controls.Add(objKW)
        End Using
        Me.KW.InnerHtml = "<!--" & Keywords & "-->"
        'Page Description
        Using objDesc As New HtmlMeta()
            objDesc.Name = "description"
            objDesc.Content = Description
            Header.Controls.Add(objDesc)
        End Using
    End Sub

    Private Sub AddSubCats()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplaySubCategories())
            Else
                tmpString.Append("<h1>Part Categories</h1>")
                tmpString.Append("<div class=""content"">Please select from our part categories on the left.</div>")
            End If
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Private Sub AddCatParts()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplayCategoryParts())
            End If
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Private Sub AddCatDesc()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplayCategoryDescription())
            End If
            AddSEOToPage(.MetaTitle, .MetaDescription, .MetaKeywords)
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Protected Overrides Sub Finalize()
        objCat = Nothing
        MyBase.Finalize()
    End Sub

End Class

Open in new window

0
 
kevp75Author Commented:
I had tried to use ThreadPool.QueueUserWorkItem() as well, with no success
0
 
CodeCruiserCommented:
I think the trouble is that page returns to browser before the threads complete. Check this tutorial

http://www.codeproject.com/Articles/38501/Multi-Threading-in-ASP-NET.aspx
0
 
kevp75Author Commented:
I can't get their code to work either
0
 
kevp75Author Commented:
test.aspx =
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" Inherits="test" Async="true" %>
<div id="Output" runat="server"></div>
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions

Partial Public Class test
    Inherits System.Web.UI.Page
    Private _request As WebRequest

    Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        AddOnPreRenderCompleteAsync(New BeginEventHandler(AddressOf BeginAsyncOperation), New EndEventHandler(AddressOf EndAsyncOperation))
    End Sub

    Private Function BeginAsyncOperation(ByVal sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal state As Object) As IAsyncResult
        _request = WebRequest.Create("http://www.o7th.com")
        Return _request.BeginGetResponse(cb, state)
    End Function

    Private Sub EndAsyncOperation(ByVal ar As IAsyncResult)
        Dim text As String
        Using response As WebResponse = _request.EndGetResponse(ar)
            Using reader As New StreamReader(response.GetResponseStream())
                text = reader.ReadToEnd()
            End Using
        End Using
        Me.Output.InnerHtml = text.Length
    End Sub

End Class

Open in new window

0
 
CodeCruiserCommented:
Do you see nothing?
0
 
kevp75Author Commented:
weird.   On a test page, yes, I see nothing.

On the page above, I get the response
0
 
kevp75Author Commented:
so how would I implement that in my needs?
0
 
CodeCruiserCommented:
I guess do everything in EndAsyncOperation function.
0
 
kevp75Author Commented:
right, but what would I do about BeginXXX and EndXXX to call these?
0
 
kevp75Author Commented:
what would they be?  BeginInvoke? and EndInvoke?
0
 
CodeCruiserCommented:
Copy all the code excep this line in Begin
    _request = WebRequest.Create("http://www.o7th.com")

In the End sub, remove all the code and add your own code which does processing.
0
 
kevp75Author Commented:
BeginGetResponse And EndGetResponse are webrequest methods
0
 
CodeCruiserCommented:
Ok. Lets replace this code

        Dim objTh1 As New System.Threading.Thread(AddressOf AddSubCats)
        With objTh1
            .Name = "SubCat"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh1 = Nothing
        Dim objTh2 As New System.Threading.Thread(AddressOf AddCatParts)
        With objTh2
            .Name = "CatParts"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh2 = Nothing
        Dim objTh3 As New System.Threading.Thread(AddressOf AddCatDesc)
        With objTh3
            .Name = "CatDesc"
            .TrySetApartmentState(Threading.ApartmentState.MTA)
            .Priority = Threading.ThreadPriority.Normal
            .Start()
            objPC.InnerHtml += "Thread ID: " & .ManagedThreadId & "<hr />"
            .Abort()
        End With
        objTh3 = Nothing



with this



Dim MyHandles As New WaitHandle() = {New ManualResetEvent(false), New ManualResetEvent(false), New ManualResetEvent(false) }

Dim Method1 As New WaitCallBack(AddSubCats)
Dim IsQueued1 as Boolean  = ThreadPool.QueueUserWorkItem(Method1, MyHandles(0))

Dim Method2 As New WaitCallBack(AddSubParts)
Dim IsQueued2 as Boolean  = ThreadPool.QueueUserWorkItem(Method1, MyHandles(1))

Dim Method3 As New WaitCallBack(AddSubDesc)
Dim IsQueued3 as Boolean  = ThreadPool.QueueUserWorkItem(Method1, MyHandles(2))


If WaitHandle.WaitAll(MyHandles, 5000, False)
   'successfull
End If




All the methods need to take a parameter State of type Object
Add the end of each method, add these two lines

Dim mre as ManualResetEvent = state
mre.Set()

Open in new window

0
 
kevp75Author Commented:
returns errors

Object not set to an instance of an object:

mre.Set()
0
 
CodeCruiserCommented:
IF you leave that part out?
0
 
kevp75Author Commented:
also.   I added in objPC.InnerHtml += 'Successful" to the successful section, and nothing shows
0
 
kevp75Author Commented:
changed:

Returns "Fail"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        objPC = Me.PartContent
        Dim tmpString As New StringBuilder
        Try
            If Not (IsNothing(QS)) Then
                StringToQuery = QS(0).ToString()
            End If
            Dim QryArr() As String = StringToQuery.Split("/")
            If UBound(QryArr) - 1 = 1 Then
                CatID = LookUps.GetCategoryID(QryArr(1), LookUps.GetCategoryID(QryArr(0)))
                tmpString.Append(ShowBreadCrumbs(CatID))
            ElseIf UBound(QryArr) - 1 = 0 Then
                IsParent = True
                CatID = LookUps.GetCategoryID(QryArr(0))
                tmpString.Append(ShowBreadCrumbs(CatID))
            End If
        Catch ex As Exception
        End Try
        objPC.InnerHtml = tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
        Dim MyHandles As WaitHandle() = New WaitHandle() {New ManualResetEvent(False), _
                                                          New ManualResetEvent(False), _
                                                          New ManualResetEvent(False)}

        Dim Method1 As New WaitCallback(AddressOf AddSubCats)
        Dim IsQueued1 As Boolean = ThreadPool.QueueUserWorkItem(Method1, MyHandles(0))

        Dim Method2 As New WaitCallback(AddressOf AddCatParts)
        Dim IsQueued2 As Boolean = ThreadPool.QueueUserWorkItem(Method2, MyHandles(1))

        Dim Method3 As New WaitCallback(AddressOf AddCatDesc)
        Dim IsQueued3 As Boolean = ThreadPool.QueueUserWorkItem(Method2, MyHandles(2))

        If WaitHandle.WaitAll(MyHandles, 5000, False) Then
            objPC.InnerHtml += "Success"
        Else
            objPC.InnerHtml += "Fail"
        End If

    End Sub

Open in new window

0
 
kevp75Author Commented:
If I change ManualResetEvent to True, it returns 'Success', however, the Methods still do not fire
0
 
kevp75Author Commented:
all 3 methods return as being queued
0
 
kevp75Author Commented:

Dim MyHandles As WaitHandle() = New WaitHandle() {New ManualResetEvent(False), _
                                                          New ManualResetEvent(False), _
                                                          New ManualResetEvent(False)}

        Dim Method1 As New WaitCallback(AddressOf AddSubCats)
        Dim IsQueued1 As Boolean = ThreadPool.QueueUserWorkItem(Method1, MyHandles(0))
        If IsQueued1 Then
            objPC.InnerHtml += "Method1 is Queued<br />"
        End If
        Dim Method2 As New WaitCallback(AddressOf AddCatParts)
        Dim IsQueued2 As Boolean = ThreadPool.QueueUserWorkItem(Method2, MyHandles(1))
        If IsQueued2 Then
            objPC.InnerHtml += "Method2 is Queued<br />"
        End If
        Dim Method3 As New WaitCallback(AddressOf AddCatDesc)
        Dim IsQueued3 As Boolean = ThreadPool.QueueUserWorkItem(Method2, MyHandles(2))
        If IsQueued3 Then
            objPC.InnerHtml += "Method3 is Queued<br />"
        End If
        If WaitHandle.WaitAll(MyHandles, 1000, False) Then
            objPC.InnerHtml += "Success"
        Else
            objPC.InnerHtml += "Fail"
        End If

Open in new window

0
 
CodeCruiserCommented:
What if you change the time out from 5000 to 15000 or more?

We need to call the Set method on the mre.
0
 
kevp75Author Commented:
I set it to 50000 and still same results
0
 
CodeCruiserCommented:
Ok. Now I have to experiment with it myself. Give me some time. I will get back to you.
0
 
kevp75Author Commented:
do I need DirectCast(state, AutoResetEvent).[Set]()

in my 3 methods?
0
 
kevp75Author Commented:
duh...that was what the:

I added in the
        Dim mre As ManualResetEvent = state
        mre.Set()

to the 3 methods, and still get the same results.  All 3 are queued, but 'Fail'
0
 
kevp75Author Commented:
Alrigt...  little confused here...    is this threading them?
Dim MyHandles As WaitHandle() = New WaitHandle() {New AutoResetEvent(False), _
                                                          New AutoResetEvent(False), _
                                                          New AutoResetEvent(False)}

        Dim Method1 As New WaitCallback(AddressOf AddSubCats)
        Dim IsQueued1 As Boolean = ThreadPool.QueueUserWorkItem(Method1, MyHandles(0))
        If IsQueued1 Then
            objPC.InnerHtml += "Method1 is Queued<br />"
        End If
        Dim Method2 As New WaitCallback(AddressOf AddCatParts)
        Dim IsQueued2 As Boolean = ThreadPool.QueueUserWorkItem(Method2, MyHandles(1))
        If IsQueued2 Then
            objPC.InnerHtml += "Method2 is Queued<br />"
        End If
        Dim Method3 As New WaitCallback(AddressOf AddCatDesc)
        Dim IsQueued3 As Boolean = ThreadPool.QueueUserWorkItem(Method3, MyHandles(2))
        If IsQueued3 Then
            objPC.InnerHtml += "Method3 is Queued<br />"
        End If

        If WaitHandle.WaitAll(MyHandles, 1, False) Then
            objPC.InnerHtml += "Success"
        Else
            objPC.InnerHtml += "Fail"
        End If

        Method1.Invoke(New AutoResetEvent(False))
        Method2.Invoke(New AutoResetEvent(False))
        Method3.Invoke(New AutoResetEvent(False))

Open in new window

0
 
kevp75Author Commented:
I get a response from this.
0
 
kevp75Author Commented:
but...the response isnt threaded....it's simply firing off the delegate
0
 
CodeCruiserCommented:
I dont think its threaded.
0
 
kevp75Author Commented:
it's not
0
 
kevp75Author Commented:
so, i've been experimenting...  LMAO

I am now registering a AsyncTask, and running one of the methods (AddSubCats)

What I am finding is that even though, .DisplaySubCategories() returns what it is supposed to (outside the Async task), inside the OnEnd it does not return anything...  although, other tasks I put inside AddSubCats (like a response.write) will fire off
Partial Class Parts_Default
    Inherits System.Web.UI.Page

    Public objPC As Object, StringToQuery As String = ""
    Public QS As Object = HttpContext.Current.Request.QueryString
    Public CatID As Long, IsParent As Boolean = False
    Public objCat As New TurboKits.Parts

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        objPC = Me.PartContent
        Dim tmpString As New StringBuilder
        Try
            If Not (IsNothing(QS)) Then
                StringToQuery = QS(0).ToString()
            End If
            Dim QryArr() As String = StringToQuery.Split("/")
            If UBound(QryArr) - 1 = 1 Then
                CatID = LookUps.GetCategoryID(QryArr(1), LookUps.GetCategoryID(QryArr(0)))
                tmpString.Append(ShowBreadCrumbs(CatID))
            ElseIf UBound(QryArr) - 1 = 0 Then
                IsParent = True
                CatID = LookUps.GetCategoryID(QryArr(0))
                tmpString.Append(ShowBreadCrumbs(CatID))
            End If
        Catch ex As Exception
        End Try

        objPC.InnerHtml = tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing

        Dim asynctask As New PageAsyncTask(AddressOf Me.OnBegin, AddressOf Me.OnEnd, Nothing, Nothing, True)
        ' Register the asynchronous task.
        RegisterAsyncTask(asynctask)
        ' Execute the register asynchronous task.
        ExecuteRegisteredAsyncTasks()


        ' AddSubCats()
        'AddCatParts()
        'AddCatDesc()

    End Sub

    Private _dlgt As New AsyncTaskDelegate(AddressOf AddSubCats), tmp As String
    Delegate Sub AsyncTaskDelegate()
    Public Function OnBegin(ByVal sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal extraData As Object) As IAsyncResult
        Dim result As IAsyncResult = _dlgt.BeginInvoke(cb, extraData)
        Return result
    End Function

    Public Sub OnEnd(ByVal ar As IAsyncResult)
        tmp = "Complete"
        _dlgt.EndInvoke(ar)
    End Sub

    Private Sub AddSubCats()
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                Me.PartContent.InnerHtml += .DisplaySubCategories()
            Else
                Me.PartContent.InnerHtml += "<h1>Part Categories</h1>"
                Me.PartContent.InnerHtml += "<div class=""content"">Please select from our part categories on the left.</div>"
            End If
        End With
        AddSEOToPage("WHAT TTHE F(*&^%%!!!!", "", "")
    End Sub

    Private Sub AddCatParts()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplayCategoryParts())
            End If
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Private Sub AddCatDesc()
        Dim tmpString As New StringBuilder
        With objCat
            If CatID > 0 Then
                .CategoryID = CatID
                .ParentCategory = IsParent
                tmpString.Append(.DisplayCategoryDescription())
            End If
            AddSEOToPage(.MetaTitle, .MetaDescription, .MetaKeywords)
        End With
        objPC.InnerHtml += tmpString.ToString()
        tmpString.Length = 0 : tmpString = Nothing
    End Sub

    Protected Overrides Sub Finalize()
        objCat = Nothing
        MyBase.Finalize()
    End Sub

    Private Function ShowBreadCrumbs(ByVal CatID As Object) As String
        Try
            If TurboKits.Security.Required(CatID) Then
                Dim tmpString As New StringBuilder, tmpA As String = "", tmpStr As String = ""
                tmpString.Append("<span class=""breadcrumb"">")
                Dim objDb As New TurboKits.DataAccessLayer
                With objDb
                    .CommandType = TurboKits.DataAccessLayer.CmdType.StoredProcedure
                    .Query = "spBreadCrumbNav"
                    .ParamNames = New String() {"@PageID"}
                    .ParamValues = New String() {CatID}
                    .ParamDataTypes = New Integer() {TurboKits.DataAccessLayer.DataType.Int}
                    .ExecuteDataReader()
                    If .TotalRecords > 0 Then
                        Dim tmp() As String
                        tmp = .ReturnValues(0, 0)(1).Split(",")
                        For i As Long = 0 To UBound(tmp)
                            If i = UBound(tmp) Then
                                tmpString.Append(tmp(i))
                            Else
                                tmpString.Append("<a href=""/Parts/?" & HttpUtility.UrlEncode(tmp(i).Replace(" ", "_")) & "/"" title=""" & tmp(i) & """>" & tmp(i) & "</a> &raquo; ")
                            End If
                        Next
                        Erase .ReturnValues
                    Else
                        tmpString.Append(String.Empty)
                    End If
                End With
                objDb = Nothing
                tmpString.Append("</span>" & vbCrLf)
                Return tmpString.ToString()
                tmpString.Length = 0 : tmpString = Nothing
            Else
                Return ""
            End If
        Catch ex As Exception
            Dim objErr As New TurboKits.ErrorManager
            objErr.Location = "/Parts/Default.aspx - ShowBreadCrumbs"
            objErr.Stack = ex.StackTrace()
            objErr.Except = ex
            objErr.ParseError()
            objErr = Nothing
        End Try
    End Function

    Private Sub AddSEOToPage(ByVal Title As String, ByVal Description As String, ByVal Keywords As String)
        'Page Title
        Me.Page.Title = Title
        'Page Keywords
        Using objKW As New HtmlMeta()
            objKW.Name = "keywords"
            objKW.Content = Keywords
            Header.Controls.Add(objKW)
        End Using
        Me.KW.InnerHtml = "<!--" & Keywords & "-->"
        'Page Description
        Using objDesc As New HtmlMeta()
            objDesc.Name = "description"
            objDesc.Content = Description
            Header.Controls.Add(objDesc)
        End Using
    End Sub


End Class

Open in new window

0
 
kevp75Author Commented:
side note on that...    DisplaySubCategories() is a function in a class in a class assembly (don't know if that makes a difference...)
0
 
kevp75Author Commented:
digging further....

DisplaySubCategories() fires off just fine, however, the db stuff inside it does not seem to want to work right..

Although...  it does what it is supposed to do outside an async call...
0
 
kevp75Author Commented:
So....why would it return what it is suppsoed to outside the asynchronicity but not within?
0
 
CodeCruiserCommented:
I am working on a demo project myself right now.
0
 
CodeCruiserCommented:
This is the code I used and the output is attached.



Partial Public Class _Default
    Inherits System.Web.UI.Page
    Dim Res As String
    Dim MyHandles As Threading.ManualResetEvent() = New Threading.ManualResetEvent() {New Threading.ManualResetEvent(False), New Threading.ManualResetEvent(False), New Threading.ManualResetEvent(False)}

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Private Sub Method1(ByVal State As Object)
        Res &= Now.ToString("HH:mm:ss") & ": Method1 started." & vbCrLf
        Threading.Thread.Sleep(1000)
        Res &= Now.ToString("HH:mm:ss") & ": Method1 finished." & vbCrLf
        CType(State, Threading.ManualResetEvent).Set()
    End Sub

    Private Sub Method2(ByVal State As Object)
        Res &= Now.ToString("HH:mm:ss") & ": Method2 started." & vbCrLf
        Threading.Thread.Sleep(3000)
        Res &= Now.ToString("HH:mm:ss") & ": Method2 finished." & vbCrLf
        CType(State, Threading.ManualResetEvent).Set()
    End Sub

    Private Sub Method3(ByVal State As Object)
        Res &= Now.ToString("HH:mm:ss") & ": Method3 started." & vbCrLf
        Threading.Thread.Sleep(2000)
        Res &= Now.ToString("HH:mm:ss") & ": Method3 finished." & vbCrLf
        CType(State, Threading.ManualResetEvent).Set()
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        Dim cb1 As Threading.WaitCallback = New Threading.WaitCallback(AddressOf Method1)
        Dim iq1 As Boolean = Threading.ThreadPool.QueueUserWorkItem(cb1, MyHandles(0))

        Dim cb2 As Threading.WaitCallback = New Threading.WaitCallback(AddressOf Method2)
        Dim iq2 As Boolean = Threading.ThreadPool.QueueUserWorkItem(cb2, MyHandles(1))

        Dim cb3 As Threading.WaitCallback = New Threading.WaitCallback(AddressOf Method3)
        Dim iq3 As Boolean = Threading.ThreadPool.QueueUserWorkItem(cb3, MyHandles(2))

        If Threading.WaitHandle.WaitAll(MyHandles, 10000, False) Then
            Response.Write(Res)
        Else
            Response.Write("<h5>Error</h5>")
        End If
    End Sub
End Class

Open in new window

ScreenShot042.jpg
0
 
kevp75Author Commented:
I am so confused right now....  it's not even funny.

I don't get why .DisplaySubCategories() won't return the data that it pulls inside of the threading processes, but will outside it?

Inside .DisplaySubCategories() is a SqlCommand that pulls data from a SQL database.  It works just fine when not being threaded.
0
 
kevp75Author Commented:
maybe my flow needs explaining?

I have a DataAccessLayer, which is simply a way I can call out to the database and do some work.

I have a BusinessLayer, which calls out to the DAL to pull what I need for records, or tells the DAL to do some work.

Then I have the page above.  Which displays the result from the BusinessLayer.

Now, it seems with theading the DAL doesn't work.  (there is no other threading going on, and non-threading it does work...  just fine as a matter of fact)

Both the DAL and BusinessLayer are in a class assembly
0
 
kevp75Author Commented:
when I use a straight SqlCommand connection right in AddSubCats, it works., but through the DAl it does not work
0
 
kevp75Author Commented:
not that it should matter, because it works every where else.

I'll do it, and get back in a few
0
 
kevp75Author Commented:
un-flippin believable.   ok.   so, it was the caching mechanism I had (have) in the DAL.

Apparently async operations do not like to cache?
0
 
kevp75Author Commented:
so... do you know of any way I can keep my caching, whilst doing teh async stuff?  

(by the way...  the async stuff made the page 3x faster [per firebug] went from 1.3s to .43s :)
0
 
CodeCruiserCommented:
That's a lot of improvement. I am not sure what caching mechanism you have and why async does not work with it.
0
 
kevp75Author Commented:
it was just HttpContext.Current.Cache...

but yeah, huge improvement.

Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.