ASHX-Generic Handler

Generic Handler : Async ASHX File

Imports System.Web
Imports System.Data.SqlClient
Imports System.Threading.Tasks

Public Class AsyncHandler
Implements IHttpHandler

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = “text/plain”

Task.Run(Async Sub()
Await AddToLogAsync(context)
Await ReadQueryStringAsync(context)
Await ReadPostFormVariablesAsync(context)
Await CallDatabaseResultAsync(context)
End Sub).GetAwaiter().GetResult()
End Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property

Private Async Function AddToLogAsync(ByVal context As HttpContext) As Task
‘ Add to log
Await Task.Delay(100)
End Function

Private Async Function ReadQueryStringAsync(ByVal context As HttpContext) As Task
‘ Read query string variables
Await Task.Delay(100)
End Function

Private Async Function ReadPostFormVariablesAsync(ByVal context As HttpContext) As Task
‘ Read post form variables
Await Task.Delay(100)
End Function

Private Async Function CallDatabaseResultAsync(ByVal context As HttpContext) As Task
‘ Call database and get result
Await Task.Delay(100)
End Function
End Class

Generic Handler: Response Immediately And Run DB Operation in Background

To respond to a request immediately and run code in the background without a callback, you can use asynchronous programming in ASP.NET. The basic idea is to return a response to the client as soon as possible, while allowing the code inside the API endpoint to run asynchronously on a background thread.

Here’s an example of how you can modify your code to achieve this:

Public Class updMsg : Inherits HttpTaskAsyncHandler

Private PhysicalPathOfThisFolder$
Private Const LogTitle$ = “updMsg”
Private ThisContext As HttpContext
Private IsDevEnv As Boolean = True
Dim EkConnStr$ = “”

Public Overrides Async Function ProcessRequestAsync(ByVal context As HttpContext) As Task
ThisContext = context
context.SkipAuthorization = True
context.Response.ContentType = “text/plain”
PhysicalPathOfThisFolder = context.Server.MapPath(“.”)
EkConnStr = ConfigurationManager.ConnectionStrings(“EkConnStrWA”).ConnectionString
Dim jsn$ = “”, Rtn$ = “done”
Dim err$ = “”
Dim Rdr As New StreamReader(ThisContext.Request.InputStream)
jsn = Rdr.ReadToEnd ‘jsn = File.ReadAllText(“d:\ekmailjson.txt”)
Await AddToLogAsync(jsn)

context.Response.ContentType = “text/json”
context.Response.Write(Rtn)

Try
Await Task.Run(Async Function()
Using con As New SqlConnection(EkConnStr)
Dim Qry$ = “insMsg”
Using cmd As New SqlCommand(Qry, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue(“@JSON”, jsn)
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
Await Task.Run(Function() sda.Fill(dt))
If dt.Rows.Count > 0 Then
Dim sts = dt.Rows(0).Item(“sts”)
err = dt.Rows(0).Item(“errMsg”)
If sts = “done” Then
Dim MsgTo$ = dt.Rows(0).Item(“MsgTo”)
‘Rtn = GetMsgReturn(MsgTo)
Rtn = dt.Rows(0).Item(“jsn”)
Await AddToLogAsync(Rtn)
End If
Else
err = “No Rec Found”
End If
End Using
End Using
End Using
End Using
End Function)
Catch ex As Exception
Err = ex.Message.ToString + vbCrLf + ex.StackTrace.ToString
Finally

End Try

If err <> “” Then
Await AddToLogAsync(err)
End If
End Function
End Class

In this example, the response is immediately returned to the client using context.Response.Write(Rtn). The code inside the Try block is then executed asynchronously on a background thread

Generic Handler (ASHX) : Add To Log Function Async

Private Async Function AddToLogAsync(ByVal LogData$) As Task
Dim retryCount As Integer = 0
While retryCount < 5 Try Using writer As StreamWriter = File.AppendText(PhysicalPathOfThisFolder & "/updMsg.log") Await writer.WriteLineAsync(LogData) End Using ' If no exception was thrown, break the loop Exit While Catch ex As Exception If TypeOf ex Is IOException AndAlso ex.Message.Contains("being used by another process") Then ' File is locked, wait and retry Await Task.Delay(100) retryCount += 1 Else ' Log the exception Await AddToLogAsync("Error: " & ex.Message & vbCrLf & ex.StackTrace) ' If this is not a file locking exception, break the loop Exit While End If End Try End While End Function

Scroll to Top