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.

Download 1 file với async Task trong C#

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

01112131415161718191101111121131141var 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.

01112131415161718191101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411string[] 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.

011121314151617181private 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

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