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:
- handle = BeginInvoke(my_function)
- do other work
- result = handle.EndInvoke()
- deal with result
Or in callback way:
- handle = BeginInvoke(my_function, callback)
- 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:
#encoding=UTF-8 import time, random import sys from delegate import * def proc(a): time.sleep(random.random()) return str(a) def proc_callback(handle, args=None): try: ret = d.end(handle) log.debug('proc return: ' + repr(ret)) except Exception,e: log.warn('end throw Exception: ' + str(e)) return 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': break data = str(n) handle = d.begin(proc, data, proc_callback, 'test') log.debug('register ' + data) d.free()