有一個代碼
當 chatlist.json 不存在時,創建它并在其中放置一個空串列
當 chatslist.json 存在時,它被反序列化
private async Task<ChatsInfo> ReadChatsList() { FileInfo file = new FileInfo(chatsListPath); if (file.Exists) { using (FileStream fs = new FileStream(chatsListPath, FileMode.Open)) { ChatsInfo chatsList = await JsonSerializer.DeserializeAsync<ChatsInfo>(fs); fs.Close(); return chatsList; } } else { ChatsInfo emptylist = new ChatsInfo(); emptylist.activedChats = new List<long>(); using (FileStream fs = new FileStream(chatsListPath, FileMode.Create)) { await JsonSerializer.SerializeAsync<ChatsInfo>(fs, emptylist, new JsonSerializerOptions { WriteIndented = true }); fs.Close(); } return emptylist; } private async void SerializeChatsList(ChatsInfo data) { using (FileStream fs = new FileStream(chatsListPath, FileMode.Open)) { await JsonSerializer.SerializeAsync<ChatsInfo>(fs, data, new JsonSerializerOptions { WriteIndented = true }); fs.Close(); } } private async Task<bool> ChatInTheList(long chat_id) { ChatsInfo chatsList = await ReadChatsList(); return chatsList.activedChats.Contains(chat_id); }
有一個條件
if(!await ChatInTheList(message.Chat.Id))
{
AddChatInList(message.Chat.Id);
}
出現錯誤,在該處出現錯誤
System.IO.IOException: "The process cannot access the file
'C:\Users\User\source\repos\tgbot\bin\linux-x64\netcoreapp3.1\chatslist.json'
because it is being used by another process."
Initially, this exception was created in this call stack:
[External code]
tgbot.Bot.ReadChatsList() в Bot.cs
[External code]
tgbot.Bot.ChatInTheList(long) в Bot.cs
[External code]
tgbot.Bot.OnMessageReceived(object, Telegram.Bot.Args.MessageEventArgs) в Bot.cs
為什么其中一個執行緒沒有關閉?我哪里做錯了?
@PanagiotisKanavos
private async void AddChatInList(long chat_id)
{
ChatsInfo chatsList = await ReadChatsList();
chatsList.activedChats.Add(chat_id);
SerializeChatsList(chatsList);
}
uj5u.com熱心網友回復:
您沒有 await AddChatInList(),因此當該方法正在運行時,另一種方法正在嘗試訪問該檔案。
另外,你想打亂你的SSD嗎?因為這將是您破壞 SSD 的方式。(不,不是真的,那些東西可以寫很多資料,但是......)每個聊天行都會導致對整個檔案的讀寫操作,這會隨著每個聊天訊息而增長。您的系統將變得難以忍受。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365681.html
標籤:C#
上一篇:字串值在方法呼叫時不會改變
