❔ Problem with Dictionary<ulong, Image> (Strange work of memory access)
Concept of my system: A system that draws a picture with stickers, each of the stickers can be moved, there can be an unlimited number of stickers.
Code with explanations in comments:
private static Dictionary<ulong, Image> UserStickerProfiles = new();public static async Task MoveSticker(Sticker sticker){ var stickerImage = await ItemManager.GetProfileItemImageAsync(itemId); // take image of sticker from file UserStickerProfiles.TryGetValue(args.User.Id, out var image); if (image == null) { image = await ProfileMethods.DrawProfileExceptStickerAsync(args.User, itemId); // draw picture without this sticker UserStickerProfiles.Add(args.User.Id, image); } image.Mutate(x => x.DrawImage(stickerImage, new Point(sticker.PositionX, sticker.PositionY), 1f)); // draw this sticker with new coordinations // saving and sending var memoryStream = new MemoryStream(); await image.SaveAsPngAsync(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); // send image to user with memortStream}
private static Dictionary<ulong, Image> UserStickerProfiles = new();public static async Task MoveSticker(Sticker sticker){ var stickerImage = await ItemManager.GetProfileItemImageAsync(itemId); // take image of sticker from file UserStickerProfiles.TryGetValue(args.User.Id, out var image); if (image == null) { image = await ProfileMethods.DrawProfileExceptStickerAsync(args.User, itemId); // draw picture without this sticker UserStickerProfiles.Add(args.User.Id, image); } image.Mutate(x => x.DrawImage(stickerImage, new Point(sticker.PositionX, sticker.PositionY), 1f)); // draw this sticker with new coordinations // saving and sending var memoryStream = new MemoryStream(); await image.SaveAsPngAsync(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); // send image to user with memortStream}
Problem: Each time you use this function, a new picture should appear with ALL stickers and the sticker that we moved to a new location. However, it happens that the sticker is duplicated and there are several of them.
The suggestion line
image.Mutate(x => x.DrawImage(stickerImage, new Point(sticker.PositionX, sticker.PositionY), 1f));
image.Mutate(x => x.DrawImage(stickerImage, new Point(sticker.PositionX, sticker.PositionY), 1f));
updates the Dictionary directly, though it shouldn't be, presumably because C# has a memory bug here.