第8章. 相互接続
この作品はAIを使って翻訳されている。ご意見、ご感想をお待ちしている:translation-feedback@oreilly.com
非同期、パラレル、リアクティブ-それぞれに適材適所があるが、どの程度うまく連携しているのだろうか?
この章では、様々な相互運用のシナリオを見て、これらの異なるアプローチをどのように組み合わせればよいかを学ぶ。あるアプローチが別のアプローチと出会う境界線では、ほとんど摩擦がない。
8.1 "Completed "イベントを持つ "非同期 "メソッドの非同期ラッパー
問題
は古い非同期パターンで、次の名前のメソッドを使う。 という名前のイベントを使う。 OperationAsync.古い非同期パターンを使って演算を行い、その結果をOperationCompletedawait 。
チップ
である。 と OperationAsyncパターンはイベントベース非同期パターン(EAP)と呼ばれている。これらを、OperationCompletedTask-Task-based Asynchronous Pattern (TAP)に従ったメソッドにラップするのだ。
解決策
TaskCompletionSource<TResult> 型を使用することで、 、非同期操作のラッパーを作成することができる。TaskCompletionSource<TResult> 型はTask<TResult> を制御し、適切なタイミングでタスクを完了させることができる。
この例では、string をダウンロードするWebClient の拡張メソッドを定義している。WebClient 型はDownloadStringAsync とDownloadStringCompleted を定義している。これらを使って、DownloadStringTaskAsync メソッドを定義することができる:
publicstaticTask<string>DownloadStringTaskAsync(thisWebClientclient,Uriaddress){vartcs=newTaskCompletionSource<string>();// The event handler will complete the task and unregister itself.DownloadStringCompletedEventHandlerhandler=null;handler=(_,e)=>{client.DownloadStringCompleted-=handler;if(e.Cancelled)tcs.TrySetCanceled();elseif(e.Error!=null)tcs.TrySetException(e.Error);elsetcs.TrySetResult(e.Result);};// Register for the event and *then* start the operation.client.DownloadStringCompleted+=handler;client.DownloadStringAsync(address);returntcs.Task;}
ディスカッション
というのも、WebClient はすでにDownloadStringTaskAsync を定義しており、async より使いやすい ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access