Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This example

Excerpt

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:

Code Block
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 object.

Add closures to the mix and its gets even simpler:

Code Block
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:

Code Block
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.")