async vs threading, when to use each option?

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

This page, http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx, in the thread section, says that a async method does not run in other thread, that if I want to use other thread, I would use Task.Run.

So I understand that async and threading are two diferents things, and each option is good for some situations. I would like to know when is better to use async and when is better to use threading.

Thanks.

回答1:

You use threads when you have constant work to do. Either directly ofr with a custom written pool. And even then you may hide it behind a custom Task Scheduler (using his own thread pool).

Threads have SOME Advantages when yo uneed control over the low Level thread Parameters - which is VERY rare. Something trivia like Setting priority is something you also can do in async (remember to set back), but sometimes you ened to set up quite some things for interop.

Still, These days threads are a very low Level API - since Tasks are around with custom schedulers, you really have VERY Little uses for threads outside a custom Task Scheduler (which may use a thread pool of custom made threads internally as low Level API).

Threads also come in Handy when yo uallocate a thread for LONG TERM. Long term is not necessarly "computational intensive". I have an API here that runs in 24 hour Loops on a custom thread - I start a thread, call into a "process data" method which calls back to me. The method Returns either on issue / error, or once per day (to be immediately restarted for the next real time data block). Obviously, being busy non stop, this is a good case for a thread, not a Task as ALL the advanced Features of a Task would be useless.

For pretty much everything else These days I use a Tasks / async.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!