Hello Matias
Is this what you are looking for?
This only works with async methods that release the mainloop in between.
Please see attached file.
Compiled with:
valac --pkg gio-2.0 async2.vala
Regards
Jörn




> 
> Basically I want to call an async method that waits for a response from
> some object. But, if after, lets say 2 seconds, it don't receive a
> response, return an error.
> 
> I attached a test case of what i think it can work, but i don't know how
> to resume/cancel an async method...
> 
> Any help is welcome
> Thanks
> Matias
> _______________________________________________
> vala-list mailing list
> [email protected]
> http://mail.gnome.org/mailman/listinfo/vala-list

interface Foo : GLib.Object {
	public signal void message_received ();
	public abstract async bool send_message (string message, Cancellable? cancellable = null);
}

// depending on the size of number the timeout will be there before everything is finished
//public static const int NUMBER = 100000;
public static const int NUMBER = 100000000;

async void run () {
	Cancellable cancellable = new Cancellable();
	uint timeout = 0;

	timeout = Timeout.add(2000, () => {
		// Timed out
		print("timed out\n");
		cancellable.cancel();
		timeout = 0;
		return false; // no repeat for the timeout
	});
	
	bool result = yield _foo.send_message ("ping", cancellable);

	if(timeout != 0) {
		Source.remove(timeout);
	}

	if(result)
		print("success\n");
	else
		print("no success\n");
}

Foo _foo;

class Test : GLib.Object, Foo {
	
	public async bool send_message (string message, Cancellable? cancellable = null) {
		
		//do something time consuming
		for(int i = 0; i<NUMBER; i++) {
			if(cancellable != null && cancellable.is_cancelled()) {
				return false;
			}
			Idle.add(send_message.callback);
			yield;
		}
		print("send message %s\n", message);
		message_received();
		return true;
	}
}

void main (string[] args) {
	_foo = new Test();//create_instance_of_foo ();
	
	_foo.message_received.connect (() => {
		print("received\n");
	});
	
	run.begin ();
	
	var loop = new GLib.MainLoop (null, false);
	loop.run ();
}

_______________________________________________
vala-list mailing list
[email protected]
http://mail.gnome.org/mailman/listinfo/vala-list

Reply via email to