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
29 changes: 27 additions & 2 deletions homework.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,26 @@ public async Task UpdateInventoryAsync(string title, int quantity)

// 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}售出{quantity}本,剩余库存:{book.Inventory}");
}
else
{
Console.WriteLine($"书籍{title}库存不足。需求:{quantity}当前库存:{book.Inventory}");
}
}
else
{
Console.WriteLine($"错误!找不到书籍:{title}");
}
}
}
}

Expand All @@ -42,6 +62,7 @@ public class BookStore
// TODO: 实现异步购书方法CheckoutAsync,调用 UpdateInventoryAsync
public async Task CheckoutAsync(string bookTitle, int quantity)
{
await _db.UpdateInventoryAsync(bookTitle, quantity);
}

public async Task SimulateMultipleUsers()
Expand All @@ -59,9 +80,13 @@ public async Task SimulateMultipleUsers()
// 提示:创建多个 Task 调用 CheckoutAsync,并传入不同书名和数量
var tasks = new List<Task>
{

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

await Task.WhenAll(tasks);

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