System.InvalidOperationException: Collection was modified; enumeration operation may not execute. O

Radagast 0 Reputation points
2023-08-08T09:26:43.0133333+00:00

StateLayoutController.SwitchToContent (System.Boolean animate)

C:\Users\xxxx.yyyyy\source\repos\mobile-app\src\App\Views\StateLayout\StateLayoutController.cs, line 51

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Here is the content of the method in question:

        public async void SwitchToContent(bool animate)
        {
            if (!layoutWeakReference.TryGetTarget(out var layout))
                return;

            var token = RebuildAnimationTokenSource(layout);

            previousState = LayoutState.None;
            await ChildrenFadeTo(layout, animate, true);

            if (token.IsCancellationRequested)
                return;

            // Put the original content back in.
            layout.Children.Clear();

            var itemsToAdd = new List<View>(originalContent.Count);
            foreach (var item in originalContent)
            {
                item.Opacity = animate ? 0 : 1;
                itemsToAdd.Add(item);
            }

            for (int i = itemsToAdd.Count - 1; i >= 0; i--)
            {
                layout.Children.Insert(i, itemsToAdd[i]);
            }

            await ChildrenFadeTo(layout, animate, false);
        }

What I've tried so far, nothing seems to work:
-Using .ToList()
-Using Thread.Delay
-Changing the foreach loop into a reverse for loop (as shown above)

  • Using locks
  • Using Device.BeginInvokeOnMainThreadAsync
    -Tried various other suggestions found online

Attached in the txt file you can see the whole log from the exception InvalidOPerationException.txt

Developer technologies .NET Xamarin
Developer technologies ASP.NET ASP.NET Core
Developer technologies .NET .NET MAUI
Developer technologies .NET Other
Developer technologies C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.