如何实现"真"异步 [英] How to achieve "true" asynchrony

查看:130
本文介绍了如何实现"真"异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在他的回答<一href="http://stackoverflow.com/questions/27790468/is-it-possible-to-await-an-io-operation-that-is-not-declared-as-async-if-not-w">this问题,斯蒂芬·克利指的是假异步和真正的不同步。

  

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

     

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

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

解决方案
  

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

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

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

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

  VAR TCS =新TaskCompletionSource&LT;布尔&GT;();
_button.Click + =(发件人,EventArgs五)=&GT; tcs.SetResult(假);
等待tcs.Task;
 

有没有非泛型 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.

这篇关于如何实现&QUOT;真&QUOT;异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆