async

Starts an asynchronous computation and returns a future for the result value.

If the supplied callable and arguments are all weakly isolated, vibe.core.core.runWorkerTask will be used to perform the computation in a separate worker thread. Otherwise, vibe.core.core.runTask will be used and the result is computed within a separate task within the calling thread.

Future!(ReturnType!CALLABLE)
async
(
CALLABLE
ARGS...
)
(
CALLABLE callable
,
ARGS args
)
if (
is(typeof(callable(args)) == ReturnType!CALLABLE)
)

Parameters

callable CALLABLE

A callable value, can be either a function, a delegate, or a user defined type that defines an opCall.

args ARGS

Arguments to pass to the callable.

Return Value

Type: Future!(ReturnType!CALLABLE)

Returns a Future object that can be used to access the result.

Examples

import vibe.core.core;
import vibe.core.log;

void test()
{
	static if (__VERSION__ >= 2065) {
	auto val = async({
		logInfo("Starting to compute value in worker task.");
		sleep(500.msecs); // simulate some lengthy computation
		logInfo("Finished computing value in worker task.");
		return 32;
	});

	logInfo("Starting computation in main task");
	sleep(200.msecs); // simulate some lengthy computation
	logInfo("Finished computation in main task. Waiting for async value.");
	logInfo("Result: %s", val.getResult());
	}
}
int sum(int a, int b)
{
	return a + b;
}

static int sum2(int a, int b)
{
	return a + b;
}

void test()
{
	// Using a delegate will use runTask internally
	assert(async(&sum, 2, 3).getResult() == 5);

	// Using a static function will use runTaskWorker internally,
	// if all arguments are weakly isolated
	assert(async(&sum2, 2, 3).getResult() == 5);
}

See Also

Meta