9 编写异步方法(异步方法封装)

237 阅读1分钟

一、如果同样的功能,既有同步方法,又有异步方法,那么首先使用异步方法。.NET6中,很多框架中的方法也都支持异步:Main、WinForm事件处理函数。

await DownloadAsync("https://www.baidu.com", "G:/1.txt");
Console.WriteLine("ok");

//无返回值
async Task DownloadAsync(string url ,string destFilePath)
{
    using (HttpClient httpClient = new HttpClient())
    {
        string html = await httpClient.GetStringAsync(url);
        await File.WriteAllTextAsync(destFilePath, html);
    }
   
}

输出结果:

image.png

int l =await DownloadAsyncLen("https://www.baidu.com", "G:/1.txt");
Console.WriteLine("文档字数:"+l);

//有返回值
async Task<int> DownloadAsyncLen(string url, string destFilePath)
{
    string html;
    using (HttpClient httpClient = new HttpClient())
    {
      html = await httpClient.GetStringAsync(url);
        await File.WriteAllTextAsync(destFilePath, html);
    }
    int len = html.Length;

    return len;
}

输出结果:

image.png

image.png

namespace WinFormsAsync
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //同步
        private void button1_Click(object sender, EventArgs e)
        {
            string a = File.ReadAllText(Path.Combine("G:/1.txt"));
            MessageBox.Show("同步:"+a.Substring(0,30));
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            string a = await File.ReadAllTextAsync("G:/1.txt");
            MessageBox.Show("异步:"+a.Substring(0, 30));
        }
    }
}

输出结果:

image.png

image.png

二、对于不支持的异步方法怎么办?Wait()(无返回值)Result(有返回值)风险:死锁。尽量不用。

NonsupportAsync();

//不支持异步方法(假设)
 void NonsupportAsync()
{
    //无返回值--Wait()
    File.WriteAllTextAsync("G:/2.txt", "NonsupportAsync").Wait();


    //有返回值--Result
    //string a = File.ReadAllTextAsync("G:/2.txt").Result;

    Task<string> t = File.ReadAllTextAsync("G:/2.txt");

    string a = t.Result;

    Console.WriteLine(a);
}

输出结果:

image.png

三、异步委托的写法

//异步委托调用
 void DelegateAsync()
{
    ThreadPool.QueueUserWorkItem(async (obj) =>
    {
        while (true)
        {
            string a = await File.ReadAllTextAsync("G:/2.txt");
            Console.WriteLine(a);
        }
    }
    );
    Console.ReadLine();
}

输出结果: image.png