Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions homework.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,26 @@ public async Task UpdateInventoryAsync(string title, int quantity)
await Task.Delay(100); // 模拟网络延迟

// TODO: 使用 lock 语句保证线程安全
// 提示:在 lock 块中查找书籍并更新库存,若库存不足则输出提示
lock (_lock)
{
var book = _books.Find(b => b.Title == title);
if (book != null)
{
if (book.Inventory >= quantity)
{
book.Inventory -= quantity;
Console.WriteLine($"成功售出 {title} x{quantity},剩余库存: {book.Inventory}");
}
else
{
Console.WriteLine($"库存不足,无法售出 {title} x{quantity},当前库存: {book.Inventory}");
}
}
else
{
Console.WriteLine($"找不到书籍: {title}");
}
}
}
}

Expand All @@ -42,6 +61,8 @@ public class BookStore
// TODO: 实现异步购书方法CheckoutAsync,调用 UpdateInventoryAsync
public async Task CheckoutAsync(string bookTitle, int quantity)
{
Console.WriteLine($"开始处理购买请求: {bookTitle} x{quantity}");
await _db.UpdateInventoryAsync(bookTitle, quantity);
}

public async Task SimulateMultipleUsers()
Expand All @@ -56,12 +77,16 @@ public async Task SimulateMultipleUsers()
Console.WriteLine("\n 开始模拟多用户购书...\n");

// TODO: 使用 Task.WhenAll 模拟多个用户并发购书
// 提示:创建多个 Task 调用 CheckoutAsync,并传入不同书名和数量
var tasks = new List<Task>
{

CheckoutAsync("C#入门", 2),
CheckoutAsync("C#入门", 3),
CheckoutAsync("异步编程", 1),
CheckoutAsync("异步编程", 2),
CheckoutAsync("异步编程", 3)
};

await Task.WhenAll(tasks);

Console.WriteLine("\n购买后库存:");
books = await _db.GetBooksAsync();
Expand Down