How async works understood correctly? - async-await

List<Results> stuff = DoSomeStuff();
await Task.run(SomeAsyncAction);
return stuff;
I have something similar to the above in my program. The task is supposed to update my database with results from an expensive calculation. Does this mean my async method would never execute the return statement until the awaitable has completed even though it already has what it needs

Correct, the method can't continue until the awaited asynchronous operation is complete.

There's an excellent explanation here:
https://pages.cs.wisc.edu/~remzi/OSTEP/threads-events.pdf
async/await is an event-loop concurrency model.

Related

Kotlin coroutines cooperative cancelation explanation

After reading the official docs on coroutine cancelation, If for the example I have the following code:
val job = scope.launch {
val userId = networkOperationOne()
//check if coroutine is still active before calling operation two?
val userDetails = networkOperationTwo(userId)
}
Should I check isActive before calling network call two?
Let's assume that job.cancel() was called while networkOperationOne() is still in progress and that I'm not calling any suspending function that automatically does the cancelation for me.
It depends on how networkOperationOne and networkOperationTwo are suspending.
They may internally be cooperative anyway, which means you do not have to check isActive.
When in doubt, throw in ensureActive() to perform the check and act accordingly.
In this case, the conditional check is negligible compared to the network request so add one in.

Xamarin.Forms.Device.StartTimer - Is There a Non-Recurring Version of This? (A Simple Delay)

Xamarin.Forms.Device.StartTimer is a convenient method to repeatedly call some code in a certain interval. This is similar to JavaScript's SetInverval() method. JavaScript also has a method to set a single delay, called SetTimeout() - it delays a certain amount of time, then calls the callback code once. Is there a SetTimeout equivalent for Xamarin.Forms, where I simply want the code to be called in the background after a certain delay?
NOTE: I know I can return false to stop the recurrence, and that's easy enough. It just seems like if you're only intending to call the callback once, it's a little semantically misleading to use this recurring timer mechanism.
StartTimer will do this
While the callback returns true, the timer will keep recurring.
Simply return false to stop the timer
You could start a Task with delay:
async Task DoSomethingOnceWithDelay(TimeSpan delay)
{
await Task.Delay(delay);
await MyTask();
}
Official doc.

Async table creation and query advantages / disadvantages

In my application I have the following:
db2.CreateTable<CategoryGroup>();
db2.CreateTable<Category>();
db2.CreateTable<CategoryGroupSource>();
db2.CreateTable<CategorySource>();
db2.CreateTable<Phrase>();
db2.CreateTable<PhraseSource>();
db2.CreateTable<Score>();
db2.CreateTable<Setting>();
From what I understand there is an Async way to do this also:
database.CreateTableAsync<TodoItem>().Wait();
Can someone explain if there is any advantage in me using the Async way and do people normally always use the Async?
Also are there likely to be benefits if I use this type of Async query:
public Task<TodoItem> GetItemAsync(int id)
{
return database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
}
When calling the methods on the main (UI) thread everything on the UI stops for as long as it takes that method to execute. If db2.CreateTable<CategoryGroup>() doesn't take up much time when doing it's thing, it shouldn't be a problem.
Doing a lot of time consuming actions straight after each other might affect your UI and make it freeze.
Calling the *Async variant of the method moves the work to a background thread, via the task API. Calling Wait() on that task, though, makes the current thread (in this case the UI thread) wait for the task to finish, and you're stuck with the same problem.
You should always await tasks: await database.CreateTableAsync<TodoItem>(). This will let it execute on a background thread and not make the current thread wait for it to finish. The next line in your code won't be executed until the Task is finished though. When you write the code, it makes the `Async variant look like it's behaving like the regular version.
Personally, I'd probably move all the methods into a task and just await that. That way you're not returning to the UI thread between each task to execute the next one:
await Task.Run(() =>
{
db2.CreateTable<CategoryGroup>();
db2.CreateTable<Category>();
db2.CreateTable<CategoryGroupSource>();
db2.CreateTable<CategorySource>();
db2.CreateTable<Phrase>();
db2.CreateTable<PhraseSource>();
db2.CreateTable<Score>();
db2.CreateTable<Setting>();
}
In this case you're making the database do all it's work on a background thread (and not freezing the UI while it's doing it). It then returns the result to the UI thread to enable you to update UI.
public Task<TodoItem> GetItemAsync(int id)
{
return database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
}

Is the order of execution of resolved Awaitables well-defined in Hack?

The example below fires off 1000 async usleep calls separated by 100μs, then blocks the main thread before joining:
<?hh
$awaitable = HH\Asio\v((new Vector(range(1, 1000)))->map((int $wait_time) ==> {
return async {
await HH\Asio\usleep($wait_time*100);
echo $wait_time."\n";
};
}));
usleep(1000000);
HH\Asio\join($awaitable);
The result in stdout (3v4l) indicates the order that control returned to the async scopes.
The program consistently spits out a monotonically-decreasing sequence from 1000 to 1, suggesting that the finished Awaitables are pushed onto a stack and popped once the thread is freed in LIFO order. Is this ordering real, and can I rely on it?
This is deliberately not specified, and may change in the future -- and has already changed before. The only thing about async functions you can rely on is that after you await them then they have executed and returned their result.
(This also means, for example, that you should not rely on what happens when you invoke an async function but don't immediately await on it.)
If you rely in the exact ordering of Awaitables being collected or executed, you are probably doing something wrong.
Awaitables are supposed to be used for IO.
Could you explain a bit more why do you need exact ordering?
Yes, this ordering *is real, as ready await handles are explicitly processed in LIFO order. However, as #pablo-alcubilla writes, it shouldn't be relied on until it enters the HHVM spec, if ever.

async methods calling sync methods

New to async and trying to understand when it makes sense to use it.
We are going to have lots methods in webapi2 calling legacy webservices.
We have lots of low level dlls (Company.Dal.dll,Company.Biz.dll) etc.. that have methods that are not async
Question
Does async has to be all the way really ?
Is there any benefit of having an high level dll (all method async) calling low level dlls (dal,biz etc legacy code) where none of the method are async?
Is it there any benefit in having just the high level component to be async and the rest syncronous?
Many thanks for clarification
Any good tutorials explaning this concept
Using async only makes sense if you actually await something. If you don't, the async method will actually be completely synchronous (and you get a warning from the compiler about it).
In this case, async doesn't have any advantages, only disadvantages: the code is more complex and less efficient.
A thread can only do one thing at a time. If procedures keep your thread busy, there is no sense in making them async.
However if there are periods where the thread in your procedure has to wait for something else to finish, your thread might do something useful instead. In those circumstances async-await becomes useful.
Eric lippert once explained async-await with a restaurant metaphor (search on the page for async-await). If you have a cook who has to wait until the bread is toasted, this cook could do something else, like cooking an egg, and get back to the toaster when the "something else" is finished, or when has to wait for something, like await for the egg to be cooked.
In software the things where your thread typically will do nothing except waiting for something to finish is when reading / writing to disk, sending or receiving data over the network etc. Those are typically actions where you can find async versions as well as non-async versions of the procedure. See for instance classes like Stream, TextReader, WebClient, etc.
If your thread has to do a lot of calculations, it is not useful to make the function async, because there is no moment your thread will not do anything but wait, so your thread won't have time to do other things.
However, if your thread could do something useful while the calculations are done, consider letting another thread do those calculations while your thread is doing the other useful stuff:
private async Task<int> MyLengthyProcedure(...)
{
Task<int> calculationTask = Task.Run( () => DoCalculations(...));
// while one of the threads is doing the calculations,
// your thread could do other useful things:
int i = DoOtherCalculations();
// or if there are calculations that could be performed
// by separate threads simultaneously, start a second task
Task<int> otherCalculationTask = Task.Run( () => DoEvenMoreCalculations(...));
// now two threads are doing calculations. This thread is still free to
// do other things
// after a while you need the result of both calculations:
await Task.WhenAll( new Task[] {calculationTask, otherCalculationTask});
// the int return value of DoCalculations and DoOtherCalculations are in
// the Result property of the task object:
int j = calculationTask.Result;
int k = otherCalculationTask.Result;
return i + j + k;
;

Resources