异步实现await和Async

异步实现方式

async和await,例程如下

using System;

using System.Drawing;

using System.Windows.Forms;

using System.Net;

using System.Net.Http;

 
 

namespace WindowsFormsApplication4

{

public
partial
class
Form1 : Form

{

public Form1()

{

InitializeComponent();

}

 
 

private
async
void button1_Click(object sender, EventArgs e)

{

string imageUrl = @”http://www.xudajun.com/wp-content/uploads/2021/09/091621_0200_1.png”;

HttpClient client = new
HttpClient();

HttpResponseMessage response = await client.GetAsync(imageUrl);

if(response.StatusCode==HttpStatusCode.OK)

{

var stream = await response.Content.ReadAsStreamAsync();

Image image = Bitmap.FromStream(stream, true);

pictureBox1.Image = image;

}

}

}

}

 
 

执行结果

 
 

异步实现的示例

private
async
void button2_Click(object sender, EventArgs e)

{

int d = await GetValueAsync(9);

MessageBox.Show(d.ToString());

}

 
 

private
static
async
Task<int> GetValueAsync(int a)

{

int c=0;

await
Task.Run(()=>

{

Thread.Sleep(10000);

c = a * a;

});

return c;

}

 
 

 
 

 
 

 
 

  

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注