-
-
Save SteveSandersonMS/2514d7671cf6c5c6368d249fba296fbb to your computer and use it in GitHub Desktop.
Async void message loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyNetworkClient { | |
public event SomeDelegate OnException; | |
public async Task ConnectAsync(string address) { | |
await this.MakeTheActualConnection(address); | |
this.BeginReceiveLoop(); | |
} | |
// It's async void! But is that bad? | |
// I know that an unhandled exception here is going to bring down the process, but where else do you want | |
// that exception to go? There's no external control flow that can reasonably receive such an exception. | |
private async void BeginReceiveLoop() { | |
while (true) { | |
try { | |
var incomingBlock = await this.networkStream.ReadAsync(); | |
if (incomingBlock == null) { | |
// Disconnected or disposed | |
return; | |
} else { | |
this.DoSomething(incomingBlock); | |
} | |
} catch (Exception ex) { | |
this.RaiseOnException(ex); | |
} | |
} | |
} | |
private void RaiseOnException(Exception ex) { | |
var evt = this.OnException; | |
if (evt) { | |
evt(ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment