The use of async await in C # async operation

Source: Internet
Author: User

1. Async with await in pairs appears async is used before method, method decent face with await.

2. Using async and await to define an async method does not create a new thread.

3.await must be a long time to sweep the task, to use Task.run (() =>{}); Similar code to execute.

4. Return to written task<type>. The following code will be executed after this execution is finished.

5. Interface does not block

Example:

Private async void Button2_Click (object sender, EventArgs e)
{
Async methods
this.button2.Enabled = false;

Long length = await accesswebasync ();
This.button2.Enabled = true;
There are some things you can do that don't depend on replies.
Otherwork (); We're going to wait for Accesswebasync to execute after it's done.

This.textBox1.Text + = String.Format ("\ n Reply byte length: {0}.\r\n", length);
Txbmainthreadid.text = Thread.CurrentThread.ManagedThreadId.ToString ();
}

private void Otherwork ()
{
This.textBox1.Text + = "\ r \ n Wait for the server to reply ... \ n".
}

Private async task<long> Accesswebasync ()
{


Await Task.run (() = {Thread.Sleep (5000); Console.WriteLine ("BBB1"); Console.WriteLine ("Bbb2"); Console.WriteLine ("Bbb3"); });
MemoryStream content = new MemoryStream ();
Await Task.run (() =
{
Initiating a Web request to MSDN
HttpWebRequest webRequest = WebRequest.Create ("http://msdn.microsoft.com/zh-cn/") as HttpWebRequest;
if (webRequest! = null)
{
return reply result
using (WebResponse response = Webrequest.getresponse ())
{
using (Stream Responsestream = response. GetResponseStream ())
{
Responsestream.copyto (content);
}
}
}
});

Txbasynmethodid.text = Thread.CurrentThread.ManagedThreadId.ToString ();
return content. Length;
}

The use of async await in C # async operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.