私の意見では、async-awaitの素晴らしい点は、発信者の応答を維持するのではなく、コードが非同期待ちではないかのように簡単に見えることです。
発信者の応答性を維持するには、TasksおよびContinueWithステートメントを使用するか、Backgroundworkerまたはその他の方法を使用してスレッドを作成することもできます。しかし、非同期待機を使用する場合は、進捗状況を覚えておく必要はありません。
public Task InitializeAsync(...)
{
await Send1stMessageAsync();
await Send2ndMessageAsync();
}
In this article Eric Lippert explained async-await using a kitchen metaphor:
あなたのコードは次のようになります。何が起こるかは、スレッドが何もできなくなるまで、最初のメッセージを送信するためにすべてを行いますが、応答を待つことです。待っていない最初の発信者に制御が渡されます。あなたが待っていなかった場合は、次のコードを持っていた場合には、例えば、あなたにあったであろう:あなたは、データが受信されたことを、あなたのスレッドに通知するためにイベントを使用することを書いた
public Task InitializeAsync(...)
{
var task1stMessage = Send1stMessageAsync();
// this thread will do everything inside Send1stMessageAsync until it sees an await.
// it then returns control to this function until there is an await here:
DoSomeThingElse();
// after a while you don't have anything else to do,
// so you wait until your first messages has been sent
// and the reply received:
await task1stMessage;
// control is given back to your caller who might have something
// useful to do until he awaits and control is given to his caller etc.
// when the await inside Send1stMessageAync is completed, the next statements inside
// Send1stMessageAsync are executed until the next await, or until the function completes.
var task2ndMessage = Send2ndMessageAsync();
DoSomethingUseful();
await task2ndMessage;
}
。 Send1stMessageAsyncを非同期関数にすることは困難ではありませんが、ホイールを再開発する必要はありません。 SerialPortStreamのようなナゲットパッケージを使用して、メッセージを送信して応答を待つ非同期関数を取得することを検討してください。
重複と呼ばれるほど近くにはありませんが、私が思い描いたデザインを見てみたいと思うかもしれません[似たような回答](http://stackoverflow.com/questions/36066568/asynchronously-checking-a-value -without-bogging-down-a-thread/36070635#36070635)を使用して、SeralPortにキューの要求を送り、非同期的に応答を待つクラスを探します。 –
ありがとう、非常に便利!似たようなものを適応させて実装することができるかどうかがわかりますが、実際にメッセージの受信を処理するイベントが必要なので、私が提案した正確な答えを使用することはできません。 –