C#5异步/等待的线程机制感觉错了吗?错了、线程、机制、感觉

2023-09-03 10:13:58 作者:你是旧梦你会牵制心脏i

为什么要有调用线程走进异步方法,直到内'等待'?

这不是很清洁,只是产生一个线程,一旦异步方法被调用。这样,你肯定知道异步方法立即返回。你不必担心什么都不做昂贵的异步方法的早期阶段。

我往往想知道一个方法是否会执行code。关于'我'的线程与否。无论是堵还是不行。这种模式似乎开在中间可能性的整个范围。

的设计师很多比我聪明,所以我敢肯定有一个很好的理由,我只想让我的头周围。

解决方案   

这不是很清洁,只是产生一个线程,一旦异步方法被调用。

的异步的方法整点是要的避免的生成一个新的线程。

您感到困惑不同步并发。异步方法不需要在另一个线程上运行是异步的。异步方法的一点是,他们让你的工作分解成一小块一小块需要在特定的顺序执行的,但不一定的,而不在同一个线程进行其他工作。

想想一个线程作为一个工人,你可以雇佣的。想想一个异步方法作为一个待办事项列表中的项目之间的停顿。如果你的待办事项清单说:去商店,买牛奶和鸡蛋,回家,做一个煎蛋,然后异步的好处是,当有人拨打你的手机买鸡蛋的步骤之间的去家的步骤,并说:你可以停止在药房在您回家的路上,拿起我的prescription?你可以接听电话并安排之前的工作的你做的煎蛋。对于非异步方法,您的电话仍然振铃,直到煎蛋做,然后你接电话。用户界面块,直到你完成你在做什么。

你的概念是,为了保持UI线程响应,一瞬间你的待办事项列表你去聘请一些人跑到商店给你,让你可以自由地采取有关电话药店。 这是昂贵的和不必要的。一切都可以留下来的与异步同一线程的,因为长时间运行的任务,还内置百分点,其中用户界面变得中断和安排更多的工作

Why have the calling thread walk into the async method until the inner 'await'?

线程

Isn't it cleaner to just spawn a thread as soon as an async method is called. That way you know for sure that the async method returns immediately. You don't have to worry about not doing anything expensive at the early stages of the async method.

I tend to like to know whether a method is going to execute code on 'my' thread or not. Whether it's blocking or not. This model seems to open a whole spectrum of in-between possibilities.

The designers are much smarter than I am so I'm sure there is a good reason, I'd just like to get my head around it.

解决方案

Isn't it cleaner to just spawn a thread as soon as an async method is called.

The whole point of "async" methods is to avoid spawning a new thread.

You are confusing asynchrony with concurrency. Asynchronous methods need not run on another thread to be asynchronous. The point of asynchronous methods is that they allow you to break up work into little pieces that need to run in a particular order, but not necessarily without doing other work on the same thread.

Think of a thread as a worker you can hire. Think of a async method as a to-do list with pauses between the items. If your to-do list says "go to the store, buy milk and eggs, go home, make an omelette", then the benefit of async is that when someone calls your cell phone between the "buy eggs" step and the "go home" step and says "can you stop by the pharmacy on your way home and pick up my prescription?" you can take the call and schedule the work before you make the omelette. With non-async methods, your phone keeps ringing until the omelette is done, and then you take the call. The UI blocks until you're done what you're doing.

Your concept is that in order to keep the UI thread responsive, the moment you get the to-do list you go hire some guy to run to the store for you, so that you're free to take the call about the pharmacy. That is expensive and unnecessary. Everything can stay on the same thread with async because the long-running task has built-in points where the UI gets to interrupt and schedule more work.