async await best practices

后端 未结 3 1917
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 12:32

I\'ve grasped the concept of async await and have been using it sporadically, but do have a couple questions regarding best practices.

  1. is it ok to use await in

3条回答
  •  死守一世寂寞
    2021-02-06 13:27

    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). Waiting 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).

提交回复
热议问题