Skip to content

Asynchronous Design Pattern

Nathaniel Sabanski edited this page Jan 20, 2016 · 6 revisions

Added by Rodrigo B. de Oliveira

This example shows the benefits of having first class functions.

For a good overview of the .net framework asynchronous design pattern take a look at this article.

Now forget all that stuff about hand coding everything yourself and take a look at this:

import System

def callback(result as IAsyncResult):
    print("callback")

def run():
    print("executing")

print("started")

result = run.BeginInvoke(callback, null)
System.Threading.Thread.Sleep(50ms)
run.EndInvoke(result)

print("done")

Yes, it is that simple. That's one of the good side effects of treating functions as objects.

Add closures to the mix and its gets even simpler:

import System

def run():
    print("executing")

print("started")
result = run.BeginInvoke({ print("called back") })
System.Threading.Thread.Sleep(50ms)
run.EndInvoke(result)

print("done")

Of course you could also do it with instance methods:

import System
import System.Threading
import System.Net

request = WebRequest.Create("http://www.go-mono.com/monologue/")

// invoke GetResponse asynchronously

result = request.GetResponse.BeginInvoke(null, null)
while not result.IsCompleted:
    Console.Write(".")
    Thread.Sleep(50ms)
Console.WriteLine()

// ready to get the response
response = request.GetResponse.EndInvoke(result)

Console.WriteLine("$(response.ContentLength) bytes.")
Clone this wiki locally