Net Core教程

dotnet c# 异步 async await

本文主要是介绍dotnet c# 异步 async await,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

完整示例 (控制台)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

class Program
{

    static async Task Main()
    {
        await JobsAsync();
        Console.WriteLine("Application ending.");
        Console.ReadKey();
    }


    static async Task JobsAsync()
    {
        CancellationTokenSource s_cts = new CancellationTokenSource();
        HttpClient s_client = new HttpClient();

        IEnumerable<string> s_urlList = new string[]
        {
                "https://docs.microsoft.com",
                "https://docs.microsoft.com/aspnet/core",
                "https://docs.microsoft.com/azure",
                "https://docs.microsoft.com/azure/devops",
                "https://docs.microsoft.com/dotnet",
        };
        var tasks = new List<Task>();
        foreach (var url in s_urlList)
        {
            tasks.Add(ProcessUrlAsync(url, s_client, s_cts.Token));
        }
        await Task.WhenAll(tasks);
    }

    static async Task ProcessUrlAsync(string url, HttpClient client, CancellationToken token)
    {
        HttpResponseMessage response = await client.GetAsync(url, token);
        byte[] content = await response.Content.ReadAsByteArrayAsync(token);
        Console.WriteLine($"{url,-60} {content.Length,10:#,#}");
        //处理结果
        //......
    }
}

任务处理

  static async Task ProcessUrlAsync(string url, HttpClient client, CancellationToken token)
    {
        HttpResponseMessage response = await client.GetAsync(url, token);
        byte[] content = await response.Content.ReadAsByteArrayAsync(token);
        Console.WriteLine($"{url,-60} {content.Length,10:#,#}");
        //处理结果
        //......
    }

任务入列

   static async Task JobsAsync()
    {
        CancellationTokenSource s_cts = new CancellationTokenSource();
        HttpClient s_client = new HttpClient();

        IEnumerable<string> s_urlList = new string[]
        {
                "https://docs.microsoft.com",
                "https://docs.microsoft.com/aspnet/core",
                "https://docs.microsoft.com/azure",
                "https://docs.microsoft.com/azure/devops",
                "https://docs.microsoft.com/dotnet",
        };
        var tasks = new List<Task>();
        foreach (var url in s_urlList)
        {
            tasks.Add(ProcessUrlAsync(url, s_client, s_cts.Token));
        }
        await Task.WhenAll(tasks);
    }

控制台调用

    static async Task Main()
    {
        await JobsAsync();
        Console.WriteLine("Application ending.");
        Console.ReadKey();
    }
这篇关于dotnet c# 异步 async await的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!