Possible Duplicate:
Brief explanation of Async/Await in .Net 4.5
I’ve been programming in C# for a while now, but I can’t get my head around how the new async / await language feature works.
I wrote a function like this:
public async Task<SocketError> ConnectAsync() {
if (tcpClient == null) CreateTCPClient();
if (tcpClient.Connected)
throw new InvalidOperationException("Can not connect client: IRCConnection already established!");
try {
Task connectionResult = tcpClient.ConnectAsync(Config.Hostname, Config.Port);
await connectionResult;
}
catch (SocketException ex) {
return ex.SocketErrorCode;
}
return SocketError.Success;
}
But clearly, there’s no point to this, right? Because I’m awaiting the result of TcpClient.ConnectAsync on the line immediately after.
But I wanted to write my ConnectAsync() function so that it itself could be awaited in another method. Is this the right approach? I’m a bit lost. 🙂
I hope you have come across the
yield returnsyntax to create an iterator. It halts the execution and then continues when the next element is needed. You can think of theawaitto do something very similar. The async result is waited for and then the rest of the method continues. It won’t be blocking, of course, as it waits.