vibe.d beta banner
get vibe.d
0.7.30

Function 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. Otherwise, vibe.core.core.runTask will be used.

Prototype

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

Parameters

NameDescription

callable

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

args

Arguments to pass to the callable.

Returns

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

See also

isWeaklyIsolated

Example

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

void test()
{
	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());
}

Example

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);
}
Authors

Sönke Ludwig

Copyright

© 2013-2016 RejectedSoftware e.K.

License

Subject to the terms of the MIT license, as written in the included LICENSE.txt file.