Skip to content

Instantly share code, notes, and snippets.

@SteveSandersonMS
Forked from SteveSanderson/somefile.cs
Last active May 9, 2016 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveSandersonMS/2514d7671cf6c5c6368d249fba296fbb to your computer and use it in GitHub Desktop.
Save SteveSandersonMS/2514d7671cf6c5c6368d249fba296fbb to your computer and use it in GitHub Desktop.
Async void message loop
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