C # 5 async / waiting for simplified explanation

Possible duplicate:
A brief explanation of Async / Await in .Net 4.5

I have been programming in C # for a while, but I can’t understand how the new async / wait function works. p>

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 is no point in that, right? Because I expect the result of TcpClient.ConnectAsync on the line immediately after.

But I wanted to write my ConnectAsync () function so that it could be expected in another method. Is it correct? I'm a little lost. :)

+6
source share
3 answers

I hope you come across yield return syntax to create an iterator. It stops execution, and then continues when the next item is needed. You can think of await to do something very similar. An asynchronous result is expected, and then the rest of the method continues. Of course, he will not block as he waits.

+4
source

Seems good, except that I believe this is the syntax:

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

Since the wait works with the "Task" return, return is not possible if the function does not have the result of the task.

Here is a 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"; } 
+2
source

Something like that:

  • tcpClient.ConnectAsync(Config.Hostname, Config.Port) will be executed asynchronously;
  • after await connectionResult execution will be saved for the calling ConnectAsync method;
  • then await connectionResult will complete the asynchronous operation, the rest of your method will be executed (for example, a callback);

The ancestors of this function:

Simplified APM with AsyncEnumerator

Additional features of AsyncEnumerator

0
source

All Articles