Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm attempting to implement a simple long-polling/comet/reverse AJAX solution, and came across the concept of delegates, specifically with the BeginInvoke and EndInvoke methods. I've built a Web Service that uses these concepts, but, having never used these, they make me a little nervous, and I have my doubts as to whether they are actually what I want.

The goal, of course, is to offload the actual processing from IIS processes onto other framework processes, for a reduction in server load when waiting on a long-poll request for data. I can't have gotten this right, but I want to know why and at least get some direction in how it might be better accomplished (not necessarily a solution, but maybe an article or some documentation).

The Web Service code:

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Threading
Imports System.Runtime.InteropServices

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Dim threadId As Integer
        Dim thing As New Things
        Dim caller As New AsyncDoStuff(AddressOf thing.doStuff)
        Dim result As IAsyncResult = caller.BeginInvoke(3000, threadId, Nothing, Nothing)

        result.AsyncWaitHandle.WaitOne()

        Dim returnValue As String = caller.EndInvoke(threadId, result)

        result.AsyncWaitHandle.Close()

        Return returnValue
    End Function
End Class

Public Class Things
    Public Function doStuff(ByVal callDuration As Integer, <Out()> ByRef threadId As Integer) As String
        ' Imagine this method was accessing a database, looking for new information, and returning when it found some
        Thread.Sleep(callDuration)
        threadId = Thread.CurrentThread.ManagedThreadId()
        Return String.Format("My call time was {0}.", callDuration.ToString())
    End Function
End Class

Public Delegate Function AsyncDoStuff(ByVal callDuration As Integer, <Out()> ByRef threadID As Integer) As String
share|improve this question

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.