Menu
CoddyTech

Async và Await

Thuộc phần C# và .NET cơ bản trong hành trình ASP.NET Core của Coddy. Bài học 19 trên 20.

Đọc tệp hoặc gọi máy chủ khiến chương trình phải chờ. Một phương thức async trả về Task (hoặc Task<T> nếu có kết quả) ngay lập tức, còn await chờ phương thức đó mà không chặn luồng, nhờ vậy luồng có thể làm việc khác trong lúc chờ. Phương thức dùng await được đánh dấu bằng async, còn các câu lệnh cấp cao nhất có thể dùng trực tiếp await.

async Task<int> LengthAsync(string path)
{
    var text = await File.ReadAllTextAsync(path);
    return text.Length;
}
var first = LengthAsync("a.txt");
var second = LengthAsync("b.txt");
int[] lengths = await Task.WhenAll(first, second);

Cả hai lần đọc chạy cùng lúc, còn Task.WhenAll chờ cả hai hoàn tất. Theo quy ước, tên các phương thức trả về một tác vụ kết thúc bằng Async. Máy chủ liên tục chờ tệp, cơ sở dữ liệu và các máy chủ khác; các trình xử lý của ASP.NET Core cũng dùng await theo cách này.

challenge icon

Thử thách

Trung bình

Hãy để export cũng ghi một tệp cho mỗi danh mục bằng phương thức tệp bất đồng bộ.

  1. Trong trường hợp export, sau dòng Exported, hãy lặp qua các khoản chi được nhóm theo danh mục.
  2. Với mỗi nhóm, hãy tạo đường dẫn exports/food.csv (danh mục, sau đó là .csv) bằng Path.Combine. Ghi các dòng của nhóm theo cùng định dạng CSV như expenses.csv bằng await File.WriteAllLinesAsync.
  3. Sau mỗi tệp, hãy in Wrote exports/food.csv cùng với đường dẫn của tệp.

Với ba khoản chi trong expenses.json, dotnet run -- export in ra:

Exported 3 expenses to exports/expenses.csv.
Wrote exports/food.csv
Wrote exports/travel.csv

và exports/travel.csv chứa một dòng Train,4.20,travel.

Thử nhé: terminal bên cạnh trình soạn thảo đã có lệnh dotnet run -- export, vậy hãy nhấn Chạy để xem ba dòng ở trên. Đổi danh mục của Groceries trong expenses.json thành home rồi nhấn Chạy lần nữa: bạn sẽ thấy dòng thứ ba, Wrote exports/home.csv.

Tự làm thử

using System.Globalization;
using System.Text.Json;

var file = "expenses.json";
var expenses = new List<Expense>();
if (File.Exists(file))
{
    expenses = JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(file)) ?? new List<Expense>();
}
var budgets = new Dictionary<string, decimal>();
if (File.Exists("budgets.json"))
{
    budgets = JsonSerializer.Deserialize<Dictionary<string, decimal>>(File.ReadAllText("budgets.json")) ?? new Dictionary<string, decimal>();
}
var count = expenses.Count;
var total = expenses.Sum(e => e.Amount);

if (args.Length == 0)
{
    Console.WriteLine("Expense Tracker");
    Console.WriteLine($"{count} expenses");
    Console.WriteLine($"Total: {total:F2}");
}
else
{
    switch (args[0])
    {
        case "add":
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: add <name> <amount> [category]");
                return 1;
            }
            if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
            {
                Console.Error.WriteLine($"Invalid amount: {args[2]}");
                return 1;
            }
            if (amount is <= 0 or > 10000)
            {
                Console.Error.WriteLine("The amount must be more than 0 and at most 10000.");
                return 1;
            }
            var category = args.Length > 3 ? args[3] : "other";
            var expense = new Expense(args[1], amount, category);
            expenses.Add(expense);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Added {expense.Name}: {expense.Amount:F2} ({expense.Category})");
            if (budgets.TryGetValue(category, out var limit))
            {
                var spent = expenses.Where(e => e.Category == category).Sum(e => e.Amount);
                if (spent > limit)
                {
                    Console.WriteLine($"Over budget for {category}: {spent:F2} of {limit:F2}");
                }
            }
            break;
        case "remove":
            if (args.Length < 2)
            {
                Console.Error.WriteLine("Usage: remove <name>");
                return 1;
            }
            Expense? match = expenses.Find(e => e.Name == args[1]);
            if (match is null)
            {
                Console.Error.WriteLine($"No expense named {args[1]}.");
                return 1;
            }
            expenses.Remove(match);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Removed {match.Name}: {match.Amount:F2}");
            break;
        case "list":
            var shown = args.Length > 1 ? expenses.Where(e => e.Category == args[1]).ToList() : expenses;
            if (shown.Count == 0)
            {
                Console.WriteLine("No expenses.");
                break;
            }
            foreach (var line in shown.Select(e => $"{e.Name}: {e.Amount:F2} ({e.Category})"))
            {
                Console.WriteLine(line);
            }
            break;
        case "top":
            var howMany = 3;
            if (args.Length > 1 && !int.TryParse(args[1], out howMany))
            {
                Console.Error.WriteLine($"Invalid number: {args[1]}");
                return 1;
            }
            var biggest = expenses.OrderByDescending(e => e.Amount).Take(howMany);
            foreach (var line in biggest.Select((e, i) => $"{i + 1}. {e.Name}: {e.Amount:F2} ({e.Category})"))
            {
                Console.WriteLine(line);
            }
            break;
        case "categories":
            var groups = expenses.GroupBy(e => e.Category).OrderByDescending(g => g.Sum(e => e.Amount));
            foreach (var g in groups)
            {
                Console.WriteLine($"{g.Key}: {g.Sum(e => e.Amount):F2} ({g.Count()})");
            }
            break;
        case "help":
            var topic = args.Length > 1 ? args[1] : "";
            var help = topic switch
            {
                "" => "Type help <command>, such as help add.",
                "add" => "add <name> <amount> [category]: saves an expense",
                "remove" => "remove <name>: deletes the first expense with that name",
                "list" => "list [category]: shows the saved expenses",
                "top" => "top [n]: shows the n biggest expenses, 3 by default",
                "categories" => "categories: shows the total of each category",
                "import" => "import <file>: adds the expenses in a CSV file",
                "export" => "export: writes every expense to exports/expenses.csv",
                _ => $"No help for {topic}.",
            };
            Console.WriteLine(help);
            break;
        case "import":
            if (args.Length < 2)
            {
                Console.Error.WriteLine("Usage: import <file>");
                return 1;
            }
            if (!File.Exists(args[1]))
            {
                Console.Error.WriteLine($"No file named {args[1]}.");
                return 1;
            }
            var imported = 0;
            var lineNumber = 0;
            foreach (var row in File.ReadAllLines(args[1]))
            {
                lineNumber++;
                try
                {
                    var parts = row.Split(',');
                    if (parts.Length != 3)
                    {
                        throw new FormatException("A line needs a name, an amount and a category.");
                    }
                    expenses.Add(new Expense(parts[0], decimal.Parse(parts[1], CultureInfo.InvariantCulture), parts[2]));
                    imported++;
                }
                catch (FormatException ex)
                {
                    Console.Error.WriteLine($"Line {lineNumber} skipped: {ex.Message}");
                }
            }
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Imported {imported} expenses from {args[1]}.");
            break;
        case "export":
            var folder = "exports";
            Directory.CreateDirectory(folder);
            var csvPath = Path.Combine(folder, "expenses.csv");
            File.WriteAllLines(csvPath, expenses.Select(e => $"{e.Name},{e.Amount.ToString("F2", CultureInfo.InvariantCulture)},{e.Category}"));
            Console.WriteLine($"Exported {expenses.Count} expenses to {csvPath}.");
            break;
        default:
            Console.Error.WriteLine($"Unknown command: {args[0]}");
            return 1;
    }
}
return 0;
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong C# và .NET cơ bản