C# TokenID: 1System.ArgumentException: элемент с тем же ключом уже был добавлен

Я работаю в C# до сих пор, и вдруг я столкнулся с этой ошибкой. Вот код ошибки, это логирование;

TokenID: 1System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at Butterfly.HabboHotel.Rooms.RoomManager.LoadRoom(UInt32 Id) in c:\Users\michael-webb\Desktop\BFLY\Butterfly Emulator\HabboHotel\Rooms\RoomManager.cs:line 207
at Butterfly.Messages.GameClientMessageHandler.PrepareRoomForUser(UInt32 Id, String Password, Boolean StaffRule) in c:\Users\michael-webb\Desktop\BFLY\Butterfly Emulator\Messages\Requests\Rooms.cs:line 528
at Butterfly.Messages.GameClientMessageHandler.OpenFlat() in c:\Users\michael-webb\Desktop\BFLY\Butterfly Emulator\Messages\Requests\Navigator.cs:line 177
at Butterfly.Messages.StaticMessageHandlers.SharedPacketLib.OpenFlat(GameClientMessageHandler handler) in c:\Users\michael-webb\Desktop\BFLY\Butterfly Emulator\Messages\StaticMessageHandlers\SharedPacketLib.cs:line 372
at Butterfly.Messages.StaticMessageHandlers.StaticClientMessageHandler.HandlePacket(GameClientMessageHandler handler, ClientMessage message) in c:\Users\michael-webb\Desktop\BFLY\Butterfly Emulator\Messages\StaticMessageHandlers\StaticClientMessageHandler.cs:line 25
at Butterfly.Messages.GameClientMessageHandler.HandleRequest(ClientMessage request) in c:\Users\michael-webb\Desktop\BFLY\Butterfly Emulator\Messages\GameClientMessageHander.cs:line 57
at Butterfly.HabboHotel.GameClients.GameClient.parser_onNewPacket(ClientMessage Message) in c:\Users\michael-webb\Desktop\BFLY\Butterfly Emulator\HabboHotel\GameClients\GameClient.cs:line 70

Вот код из строки 207 RoomManager.cs -- loadedRooms.Add(Id, Room); Который является частью этой пустоты;

   internal Room LoadRoom(UInt32 Id)
    {
        if (IsRoomLoaded(Id))
        {
            return GetRoom(Id);
        }
        try
        {
            if (loadedRooms.ContainsValue(GetRoom(Id)))
                return GetRoom(Id);
        }
        catch { }

        RoomData Data = GenerateRoomData(Id);

        if (Data == null)
            return null;

        Room Room = new Room(Data);

        //Room Room = new Room(Data.Id, Data.Name, Data.Description, Data.Type, Data.Owner, Data.Category, Data.State,
        //    Data.UsersMax, Data.ModelName, Data.CCTs, Data.Score, Data.Tags, Data.AllowPets, Data.AllowPetsEating,
        //    Data.AllowWalkthrough, Data.Hidewall, Data.Icon, Data.Password, Data.Wallpaper, Data.Floor, Data.Landscape, Data, Data.AllowRightsOverride);

        lock (roomsToAddQueue.SyncRoot)
        {
            roomsToAddQueue.Enqueue(Room);
        }


        Room.InitBots();
        Room.InitPets();

        //Logging.WriteLine("[RoomMgr] Loaded room: \"" + Room.Name + "\" (ID: " + Id + ")");
        loadedRooms.Add(Id, Room);
        return Room;
    }

Вот код строки 528 Rooms.cs - Room room2 = ButterflyEnvironment.GetGame().GetRoomManager().LoadRoom(Id); - Что является частью этой пустоты;

internal void PrepareRoomForUser(uint Id, string Password, bool StaffRule = false)
    {
        if (((this.Session != null) && (this.Session.GetConnection() != null)) && (this.Session.GetHabbo() != null))
        {
            this.ClearRoomLoading();
            QueuedServerMessage message = new QueuedServerMessage(this.Session.GetConnection());
            if (ButterflyEnvironment.ShutdownStarted)
            {
                this.Session.SendNotif(LanguageLocale.GetValue("shutdown.alert"));
            }
            else
            {
                if (this.Session.GetHabbo().InRoom)
                {
                    Room room = ButterflyEnvironment.GetGame().GetRoomManager().GetRoom(this.Session.GetHabbo().CurrentRoomId);
                    if (room != null)
                    {
                        room.GetRoomUserManager().RemoveUserFromRoom(this.Session, false, false);
                        this.Session.CurrentRoomUserID = -1;
                    }
                }
                Room room2 = ButterflyEnvironment.GetGame().GetRoomManager().LoadRoom(Id);
                if ((((room2 != null) && (this.Session != null)) && (this.Session.GetHabbo() != null)) && (!this.Session.GetHabbo().IsTeleporting || (this.Session.GetHabbo().TeleportingRoomID == Id)))
                {
                    this.Session.GetHabbo().LoadingRoom = Id;
                    this.CurrentLoadingRoom = room2;
                    if (this.Session.GetHabbo().SpectatorMode && (this.Session.GetHabbo().Rank < 4))
                    {
                        this.Session.GetHabbo().SpectatorMode = false;
                    }
                    if (!StaffRule)
                    {
                        IQueryAdapter adapter;
                        uint id;
                        using (adapter = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                        {
                            adapter.setQuery("SELECT * FROM users WHERE id = '" + this.Session.GetHabbo().Id + "'");
                            foreach (DataRow row in adapter.getTable().Rows)
                            {
                                id = Convert.ToUInt32(row["lock_room"]);
                                string str = Convert.ToString(row["lock_rooms"]);
                                if (!((id <= 0) || str.Contains(Convert.ToString(room2.RoomId))))
                                {
                                    RoomData data = ButterflyEnvironment.GetGame().GetRoomManager().GenerateRoomData(id);
                                    this.Session.GetMessageHandler().PrepareRoomForUser(id, data.Password, true);
                                }
                            }
                        }

В остальном не о чем беспокоиться. Это просто другие вещи, как только я могу вставить это. Насколько я верю, он пытается что-то сделать с Id дважды, а это не должно быть? Я никогда не сталкивался с этой ошибкой раньше, поэтому я теряюсь в том, что делать. Кто-то может заставить меня идти?

1 ответ

Похоже, что вы сохраняете загруженные комнаты по идентификатору в loadedRooms с заявлением, отмеченным ошибкой:

loadedRooms.Add(Id, Room);

Когда вы проверяете, существует ли комната в этом списке, вы проверяете по значению. Если вы не переопределите метод equals вашего объекта Room для сравнения по id, ваш вызов ContainsValue метод на loadedRooms с новой комнатой каждый раз (так как вы звоните GetRoom передать в качестве параметра).

Ваш код не разделяет тип данных вашего loadedRooms, но кажется, что это общий словарь, типизированный для типа Id и Room. Если так, то вместо использования ContainsValueпопробуйте ContainsKey на одном только идентификаторе.

if (loadedRooms.ContainsKey(Id))
   return GetRoom(Id);

См.: https://msdn.microsoft.com/en-us/library/kw5aaea4%28v=vs.110%29.aspx

Другие вопросы по тегам