Toemsel / Network

C# Network Library

Home Page:https://push-force.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

possible infinite loop problem at runtime

acard0 opened this issue · comments

commented

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);
    }
}

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