Last active
May 11, 2016 23:56
-
-
Save SteveSanderson/e437a7165e15e7fa08182c1ab6207280 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 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); | |
} | |
} | |
} | |
} |
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
Well, if you are willing to take a dependency on reactive extensions, you could solve this quite elegantly.
Observables should be your home ground :)