Context in Visual Basic .NET
Here’s the translation of the Go code to Visual Basic .NET, along with explanations in Markdown format suitable for Hugo:
In the previous example, we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of cancellation control. The CancellationToken
in .NET carries cancellation signals across API boundaries and threads.
Imports System
Imports System.Net
Imports System.Threading
Imports System.Threading.Tasks
Module Program
Async Function Hello(ByVal context As HttpListenerContext, ByVal cancellationToken As CancellationToken) As Task
' A CancellationToken is created for each request
Console.WriteLine("server: hello handler started")
Try
' Wait for a few seconds before sending a reply to the client.
' This could simulate some work the server is doing.
' While working, keep an eye on the cancellationToken for a signal
' that we should cancel the work and return as soon as possible.
Await Task.Delay(10000, cancellationToken)
Dim response = context.Response
Dim responseString = "hello\n"
Dim buffer = System.Text.Encoding.UTF8.GetBytes(responseString)
response.ContentLength64 = buffer.Length
Await response.OutputStream.WriteAsync(buffer, 0, buffer.Length)
Catch ex As OperationCanceledException
' The cancellationToken's IsCancellationRequested property
' returns true if the operation was canceled.
Console.WriteLine($"server: {ex.Message}")
context.Response.StatusCode = 500
Dim errorMessage = "Operation was canceled"
Dim errorBuffer = System.Text.Encoding.UTF8.GetBytes(errorMessage)
context.Response.ContentLength64 = errorBuffer.Length
Await context.Response.OutputStream.WriteAsync(errorBuffer, 0, errorBuffer.Length)
Finally
Console.WriteLine("server: hello handler ended")
End Try
End Function
Sub Main(args As String())
' As before, we set up our listener on the "/hello" route, and start serving.
Dim listener = New HttpListener()
listener.Prefixes.Add("http://localhost:8090/hello/")
listener.Start()
Console.WriteLine("Listening...")
While True
Dim context = listener.GetContext()
Dim cts = New CancellationTokenSource()
cts.CancelAfter(TimeSpan.FromSeconds(5)) ' Cancel after 5 seconds
Task.Run(Function() Hello(context, cts.Token))
End While
End Sub
End Module
To run the server:
- Save the code in a file named
Context.vb
. - Compile the code:
$ vbc Context.vb
- Run the compiled executable:
$ Context.exe
Listening...
Now, to simulate a client request to /hello
, you can use a web browser or a tool like curl. The server will wait for 10 seconds before responding, but the operation will be canceled after 5 seconds due to the CancellationTokenSource
.
If you open http://localhost:8090/hello/
in a web browser, you should see output similar to this in the console:
server: hello handler started
server: The operation was canceled.
server: hello handler ended
In this example, we’ve used CancellationToken
to implement a similar behavior to Go’s context.Context
. The CancellationToken
allows us to propagate cancellation requests to operations that support cancellation.
The HttpListener
class is used to create a simple HTTP server, similar to Go’s http.ListenAndServe
. The Task.Delay
method simulates a long-running operation, which can be canceled using the CancellationToken
.
This example demonstrates how to use cancellation in asynchronous operations in VB.NET, which is conceptually similar to using contexts for cancellation in Go.