async await best practices

后端 未结 3 1913
被撕碎了的回忆
被撕碎了的回忆 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:10

    Good morning,

    I would rather use a regular task with the TaskCreationOption set to 'LongRunning' in your first scenario than the async/await pattern. This way your whole while block would be executed in one long running task. When using await inside each while loop you would start a new task with every loop - would work, but it's maybe not so optimal ;-)

    Regarding your second question, I'm sorry but I don't get your point.

    Hope this helps.

    0 讨论(0)
  • 2021-02-06 13:14

    It is not ok to use a loop to keep fething data that may be present.. You can create an async call that upon completion will automaticlly invoke a callback method.. the "waiting" phase in that case will happen in the OS mechanisms which treat this waiting phase in optimum way to the OS being used.

    Take a look here for further study of the subject: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题