如何实现"真"异步如何实现、QUOT

由网友(下课的时候活一般的疯逼)分享简介:在他的回答this问题,斯蒂芬·克利指的是假异步和真正的不同步。还有一个更简单的方法来安排工作,线程池:Task.Run 真正的不同步是不可能的,因为你有一个阻塞方法您必须使用。因此,所有你能做的就是一种变通方法 - 假异步,又称阻塞线程池线程。是如何那么有可能实现真正的不同步,就像 System.Threading....

在他的回答this问题,斯蒂芬·克利指的是假异步和真正的不同步。

  

还有一个更简单的方法来安排工作,线程池:Task.Run

     

真正的不同步是不可能的,因为你有一个阻塞方法   您必须使用。因此,所有你能做的就是一种变通方法 - 假   异步,又称阻塞线程池线程。

是如何那么有可能实现真正的不同步,就像 System.Threading.Tasks.Task 的各种方法?是不是所有的真正的异步的方法正好挡住了一些其他线程的操作,如果你挖得足够深?

解决方案   

是不是所有的真正的异步的方法正好挡住了一些其他线程的操作,如果你挖得足够深?

没有。真正的异步操作不需要一个线程在整个操作和使用一个限制可扩展性和伤害性能

在最的真正的异步操作的I / O的,能得到太多过于复杂的理解。 (对于深潜阅读有一个由斯蒂芬·克利里没有线程)。

让我们说,例如,你想要计谋用户的按钮点击。因为有一个 Button.Click 事件,我们可以使用 TaskCompletionSource 异步等待事件被提出:

  VAR TCS =新TaskCompletionSource<布尔>();
_button.Click + =(发件人,EventArgs五)=> tcs.SetResult(假);
等待tcs.Task;
 
如何用Go实现一个异步网络库

有没有非泛型 TaskCompletionSource 所以我用一个布尔一个具有虚拟值。这将创建一个工作未连接到一个线程,它只是一个同步结构,当用户点击将只需要完成按钮(通过的setResult )。您可以等待工作的年龄没有任何阻塞的线程。

Task.Delay 为此事与实施非常类似于一个 System.Threading.Timer 即完成了期待已久的任务在其回调。

In his answer to this question, Stephen Cleary refers to "fake" asynchrony and "true" asynchrony.

there's a much easier way to schedule work to the thread pool: Task.Run.

True asynchrony isn't possible, because you have a blocking method that you must use. So, all you can do is a workaround - fake asynchrony, a.k.a. blocking a thread pool thread.

How then is it possible to achieve true asynchrony, like the various methods in System.Threading.Tasks.Task? Aren't all "truly asynchronous" methods just blocking operations on some other thread if you dig deep enough?

解决方案

Aren't all "truly asynchronous" methods just blocking operations on some other thread if you dig deep enough?

No. Truly asynchronous operations don't need a thread throughout the entire operation and using one limits scalability and hurts performance.

While most truly asynchronous operations are I/O ones, that can get too overly complicated to understand. (For a deep dive read There Is No Thread by Stephen Cleary).

Let's say for example that you want to await a user's button click. Since there's a Button.Click event we can utilize TaskCompletionSource to asynchronously wait for the event to be raised:

var tcs = new TaskCompletionSource<bool>();
_button.Click += (sender, EventArgs e) => tcs.SetResult(false);
await tcs.Task;

There's no non-generic TaskCompletionSource so I use a bool one with a dummy value. This creates a Task which isn't connected to a thread, it's just a synchronization construct and will only complete when the user clicks that button (through SetResult). You can await that Task for ages without blocking any threads whatsoever.

Task.Delay for that matter is implemented very similarly with a System.Threading.Timer that completes the awaited task in its callback.

阅读全文

相关推荐

最新文章