C# - Task / Async / Await

Ví dụ về Task, lập trình async/await trong C# với nhiều trường hợp sử dụng thông dụng.

Downloading

123456789101112131415161718192021222324252627282930313233343536373839404142using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Downloader
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] urls = {
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-3/lop-frontend-k5-2.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-3/lop-game-engine-k5-2.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k11-1.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k12-1.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k13-1.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k14-1.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/dao-tao-doanh-nghiep/bosch/dao-tao-ios-bosch-1.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/dao-tao-doanh-nghiep/bosch/dao-tao-machine-learning.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/seminar-workshop/vaa/tai-tro-vaa-led-design-6.jpg",
                "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/dao-tao-doanh-nghiep/savista/dao-tao-savista-react-native.jpg"
            };

            for (int i = 0; i < urls.Length; i++)
            {
                var req = HttpWebRequest.Create(urls[i]);
                var res = req.GetResponse();

                using (Stream output = File.OpenWrite(i.ToString() + ".jpg"))
                {
                    res.GetResponseStream().CopyTo(output);
                }

                Console.WriteLine("Downloading: " + urls[i]);
            }
        }
    }
}

Download 1 file với async Task trong C#

Demo cơ bản về 1 task với C#. Download 1 file async.

123456789101112131415var task = new Task<int>(() =>
{
    var req = HttpWebRequest.Create("https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k14-1.jpg");
    var res = req.GetResponse();

    using (Stream output = File.OpenWrite("task.jpg"))
    {
        res.GetResponseStream().CopyTo(output);
    }
    return 0;
});

task.Start();
task.Wait();    // await task;
Console.WriteLine(task.Result);

Download nhiều file với async Task trong C#

Download danh sách file Async.

123456789101112131415161718192021222324252627282930313233343536373839404142string[] urls = {
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-3/lop-frontend-k5-2.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-3/lop-game-engine-k5-2.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k11-1.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k12-1.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k13-1.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/lop-hoc-1/lop-cpp-k14-1.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/dao-tao-doanh-nghiep/bosch/dao-tao-ios-bosch-1.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/dao-tao-doanh-nghiep/bosch/dao-tao-machine-learning.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/seminar-workshop/vaa/tai-tro-vaa-led-design-6.jpg",
    "https://www.stdio.vn/statics/external_data/files/training_stdio_vn/gallery/dao-tao-doanh-nghiep/savista/dao-tao-savista-react-native.jpg"
};

var tasks = new List<Task<int>>();

for (int i = 0; i < urls.Length; i++) 
{
    var i2 = i;
    var task = new Task<int>(() =>
    {
        Console.WriteLine(i2.ToString() + " : " + urls[i2]);
        var req = HttpWebRequest.Create(urls[i2]);
        var res = req.GetResponse();

        using (Stream output = File.OpenWrite(i2.ToString() + ".jpg"))
        {
            res.GetResponseStream().CopyTo(output);
        }

        return i2;
    });

    tasks.Add(task);
    task.Start();
}

Task.WaitAll(tasks.ToArray());

for (var task in tasks)
{
    Console.WriteLine(task.Result);
}

C# nén files

Code mẫu nén các file theo định dạng zip.

123456789private static void ZipFilesToFile(string desFileName, string[] srcFileNames)
{
    var zip = ZipFile.Open(desFileName, ZipArchiveMode.Create);
    foreach (var fileName in srcFileNames)
    {
        zip.CreateEntryFromFile(fileName, Path.GetFileName(fileName), CompressionLevel.Optimal);
    }
    zip.Dispose();
}

Đo thời gian thực thi

123var watch = Stopwatch.StartNew();
watch.Stop();
watch.ElapsedMilliseconds;