6

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. :)

Community
  • 1
  • 1
Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
  • 1
    If you want to have an `async` method with just success/failure (no "result" value), then return `Task` instead of `Task`. Returning error codes is not a normal practice in .NET. – Stephen Cleary Jan 11 '13 at 18:30
  • Stephen: I actually want to return the SocketError (if there is one), or SocketError.Success if there is none. However, are you saying it would be better to just let any SocketException be propogated to the caller? – Xenoprimate Jan 11 '13 at 18:34
  • @Motig Yes, that's what he's saying. – Servy Jan 11 '13 at 18:34
  • 1
    This series of articles might help you. Start from the bottom; they are in reverse chronological order. http://blogs.msdn.com/b/ericlippert/archive/tags/async/ – Eric Lippert Jan 11 '13 at 19:40

3 Answers3

4

I hope you have come across the yield return syntax to create an iterator. It halts the execution and then continues when the next element is needed. You can think of the await to 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.

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • Yes, I have. The way I understood it, yield return would only return elements in the collection as they were required. So are you saying that the tcpClient.ConnectAsync() method won't block until some field on tcpClient is accessed from another area of the program? – Xenoprimate Jan 11 '13 at 18:50
  • @Motig - In this case, not until the result of the async operation is available. – manojlds Jan 11 '13 at 19:05
2

Seems good except I believe this is the syntax:

await tcpClient.ConnectAsync(Config.Hostname, Config.Port);

Because await works on the "Task" return there is no return unless the function has a Task result.

Here is the very clear example from microsoft

private async void button1_Click(object sender, EventArgs e)
{
    // Call the method that runs asynchronously.
    string result = await WaitAsynchronouslyAsync();

    // Call the method that runs synchronously.
    //string result = await WaitSynchronously ();

    // Display the result.
    textBox1.Text += result;
}

// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
    await Task.Delay(10000);
    return "Finished";
}

// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
    // Add a using directive for System.Threading.
    Thread.Sleep(10000);
    return "Finished";
}
Hogan
  • 69,564
  • 10
  • 76
  • 117
0

Something like this:

  • tcpClient.ConnectAsync(Config.Hostname, Config.Port) will run asynchronously;
  • after await connectionResult the execution will be retured to caller of ConnectAsync method;
  • then await connectionResult will finish it's asynchronous work, rest of your method will be executed (like callback);

Ancestor of this feature:

Simplified APM with the AsyncEnumerator

More AsyncEnumerator Features

Alexander Balte
  • 900
  • 5
  • 11