Asynchronous method calls
Simon McVittie
simon.mcvittie at collabora.co.uk
Wed May 9 05:55:00 PDT 2007
On Wed, 09 May 2007 at 12:02:46 +0200, Luigi Paioro wrote:
> Suppose I have an object which exposes a method myMethod(arg1, arg2,
> ...). Now I want to call it 3 times asynchronously with different
> arguments each time:
>
> call 1: myMethod(1, 2, 3, ...)
> call 2: myMethod(6, 2, 4, ...)
> call 3: myMethod(8, 10, 3, ...)
>
> Using reply_handler and error_handler I easily link the responses to a
> suitable callback function. As a result I can have 3 callbacks which are
> in a different time order respect the calls:
>
> response 1: callback of call 2
> response 2: callback of call 3
> response 3: callback of call 1
>
> The problem is that I cannot recognize each response to which original
> call are related (and sometime it can be important). I could do it
> passing a call ID as an argument and getting it from the response, but
> I'm wondering whether there could be another inner mechanism in DBus
> itself or not.
There is in fact a message ID internally, but dbus-python doesn't expose it
(unless you're using dbus.lowlevel and building messages yourself - but
don't do that if you can help it).
In dbus-python you can easily construct a new callback for each call, using
nested functions or lambdas, which is why I don't provide a "user_data"
argument like dbus-glib would.
For instance, suppose your service exports Add(i, i) -> i. You currently
have:
def print_reply(sum):
print "something + something = %d" % sum
def add_and_print_reply():
my_iface.Add(1, 2, reply_handler=print_reply, error_handler=explode)
my_iface.Add(3, 4, reply_handler=print_reply, error_handler=explode)
You could change this to:
def print_reply(a, b, sum):
print "%d + %d = %d" % sum
def add_and_print_reply():
def rh(sum):
print_reply(1, 2, sum)
my_iface.Add(1, 2, reply_handler=rh, error_handler=explode)
def rh(sum):
print_reply(3, 4, sum)
my_iface.Add(3, 4, reply_handler=rh, error_handler=explode)
If you expect this to be a frequent use case I could add a mechanism to
get the original arguments passed to the reply handler, but I suspect
that's needless complexity.
Simon
More information about the dbus
mailing list