Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 5 async / await simplistic explanation [duplicate]

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

like image 269
Xenoprimate Avatar asked Jan 11 '13 18:01

Xenoprimate


Video Answer


2 Answers

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.

like image 109
manojlds Avatar answered Oct 14 '22 17:10

manojlds


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";
}
like image 42
Hogan Avatar answered Oct 14 '22 18:10

Hogan