List of outside changes during retry

I have the following code:

    private static List<String> MyList;

    static void Main()
    {
        MyList = new List<String>();

        var websocketClient = new WebSocket("wss://ws.mysite.com");
        websocketClient.MessageReceived += IterateMyList;

        var updateListTimer = new Timer();
        updateListTimer.Elapsed += UpdateMyList;

        Console.ReadLine();
    }

    public static void IterateMyList(object sender, EventArgs e)
    {
        foreach (var item in MyList)
        {
            //Do Something with the item
        }
    }

    public static void UpdateMyList(object sender, EventArgs e)
    {
        // Add new items to and remove items from MyList. 
    }

      

What happens when the tick timer and new Websocket message messages collide?

IterateMyList () will iterate over MyList and UpdateMyList () will update it at the same time.

Will I get an exception?

+3


source to share


1 answer


If you try to insert while iterating, you will throw an exception and receive a "Read or write protected memory" error.



To solve this problem, use ConcurrentBag<T>

or another parallel collection . These objects Collection

are thread safe. If you don't need ordering, I recommend using ConcurrentBag

for performance reasons.

+1


source







All Articles