Delegate in Python(Python Asynchronous Programming)

Views: 12636 | Add Comments

The .NET Framework enables you to call any method asynchonously, by the two methods BeginInvoke and EndInvoke. The BeginInvoke method is used to register a function execution to Delegate(background threads), it quickly returns, so you can execute other codes after. In later time, you can use EndInvoke to get the return of the execution of that registered function, or you may had register a Callback function in the mean time you register that function, so this Callback will be automatically executed.

The structure of source code can be demonstrate in this steps:

  1. handle = BeginInvoke(my_function)
  2. do other work
  3. result = handle.EndInvoke()
  4. deal with result

Or in callback way:

  1. handle = BeginInvoke(my_function, callback)
  2. do other work

Python does not support Asynchronous, so I made a Delegate class, you can do Asynchronous Programming in the same way like .NET Framework does:

import time, random
import sys
from delegate import *

def proc(a):
    return str(a)

def proc_callback(handle, args=None):
        ret = d.end(handle)
        log.debug('proc return: ' + repr(ret))
    except Exception,e:
        log.warn('end throw Exception: ' + str(e))

d = Delegate()
d.init(2) # number of workers

n = 0
while True:
    n += 1
    log.debug("Press 'q' to quit, Enter to continue.")
    line = sys.stdin.readline().strip()
    if line == 'q':
    data = str(n)
    handle = d.begin(proc, data, proc_callback, 'test')
    log.debug('register ' + data)


Download source code: pap.zip API doc

Posted by ideawu at 2010-08-28 17:00:29

Leave a Comment