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