I\'ve grasped the concept of async await and have been using it sporadically, but do have a couple questions regarding best practices.
is it ok to use await in
I've grasped the concept of async await and have been using it sporadically, but do have a couple questions regarding best practices.
I have an intro to async/await blog post that goes into more detail than most intros and also introduces several best practices.
is it ok to use await in a while(condition) loop to keep fetching data that may be present, until the while condition changes, e.g. stopProcessingMessages = false.
You want to avoid tight loops. So the while (condition) GetDataIfPresent();
is going to consume a lot of CPU.
Alternatively, you could use an async
method that returned null
(or whatever) if stopProcessingMessages
is true
. In this case, your code would be while (true)
, and a more TAP-like solution would be to use CancellationSource
instead of a flag.
Also take a look at TPL Dataflow; it sounds like it may be useful for your kind of situation.
console application, or even a windows service. what is the best practice to initially kick off that first await task
For console apps, you could Wait
on the top-level task. This is an acceptable exception to the usual guideline (which is to await
instead of Wait
). Wait
ing will burn a thread for the duration of the console app, but that's usually not important enough to warrant a more complex solution. If you do want to install a single-threaded context for your console app, you could use AsyncContext.Run from my AsyncEx library.
For Win32 services, you usually do need to start your own thread. You can use Task.Run
for this (if you want a multithreaded context), or AsyncContextThread
from AsyncEx (if you want a single-threaded context).