Skip to content

Instantly share code, notes, and snippets.

@SteveSanderson
Last active May 11, 2016 23:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SteveSanderson/e437a7165e15e7fa08182c1ab6207280 to your computer and use it in GitHub Desktop.
Save SteveSanderson/e437a7165e15e7fa08182c1ab6207280 to your computer and use it in GitHub Desktop.
Async void message loop
public class MyNetworkClient {
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) {
var incomingBlock = await this.networkStream.ReadAsync();
if (incomingBlock == null) {
// Disconnected or disposed
return;
} else {
this.DoSomething(incomingBlock);
}
}
}
}
@milutinovici
Copy link

Well, if you are willing to take a dependency on reactive extensions, you could solve this quite elegantly.

var obs = Observable.FromAsync(this.networkStream.ReadAsync());
obs.Subscribe(block => DoSomething(block), e => ....);

Observables should be your home ground :)

@michaellperry
Copy link

Here's a base class that safely turns task-returning methods into async void, and exposes the exception and busy indicator as observable properties. https://github.com/michaellperry/rovermob/blob/master/RoverMob/Tasks/Process.cs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment