Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

possible infinite loop problem at runtime #94

Open
acard0 opened this issue Jan 25, 2023 · 1 comment
Open

possible infinite loop problem at runtime #94

acard0 opened this issue Jan 25, 2023 · 1 comment
Labels
bug Marks an issue as a critical bug that needs to be fixed ASAP.

Comments

@acard0
Copy link

acard0 commented Jan 25, 2023

ConcurrentBag is an unordered collection therefore attempting to remove spesific item can cause infinite loop and ConcurrentBag<>.TryTake can return null value.

public static void Remove<T>(this ConcurrentBag<T> bag, T item)
{
while (bag.Count > 0)
{
bag.TryTake(out T result);
if (result.Equals(item))
{
break;
}
bag.Add(result);
}
}

Test case (.NET 6.0);

var bag = new ConcurrentBag<string>();
bag.Add("hi");
bag.Add("123");

var time = DateTime.Now;

// works
Console.WriteLine($"Attempting to remove item: {bag.First()}");
Remove(bag, bag.ElementAt(0));
Console.WriteLine($"Deltatime is : {(DateTime.Now - time).TotalMilliseconds}ms");

// fails
Console.WriteLine($"Attempting to remove item: {bag.First()}");
Remove(bag, bag.ElementAt(1));
Console.WriteLine($"Deltatime is : {(DateTime.Now - time).TotalMilliseconds}ms");

void Remove<T>(ConcurrentBag<T> bag, T item)
{
    while (bag.Count > 0)
    {
        bag.TryTake(out T result);

        if (result.Equals(item))
        {
            break;
        }

        bag.Add(result);
    }
}
@Toemsel Toemsel added the bug Marks an issue as a critical bug that needs to be fixed ASAP. label Mar 27, 2023
@Toemsel
Copy link
Owner

Toemsel commented Mar 27, 2023

Yes, you are completely right! Thanks for the report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Marks an issue as a critical bug that needs to be fixed ASAP.
Projects
None yet
Development

No branches or pull requests

2 participants