0

I am using the code sample below -

Program.cs has a list of clients as:

public static List<Client> clients = new List<Client>();

with an event handler for click on button1

 private void button1_Click(object sender, EventArgs e)
 {
     Client client = new Client(combobox1.selecteditem);
     Program.clients.Add(client);
 }

Client.cs

All variables are non-static and public. There is an eventhandler where on packet receive, a class is called, this class is then filtered and processed

it is called in the following code:

public void recieved(short op, string str, Client c)
{
    switch (op)
    {
        case (short)OpCodes.matches:
        {
            c.something(c, str);
            break;
        }
    }
}

Handler.cs

public void something(Client c, string movement)
{
    if (movement == null)
        c.coords = movement;
    c.freeSpot = true;
}

And in the above ^ the variables would overlap and freespot would be made true throughout all the instances.

It will work fine with one instance. But I'm trying to compile with multiple instances. So creating a button_onclick would create a new instance using the above.

As the program is running, it runs flawlessly on one instance, but with 2+ instances, the variables in MyClass start to overlap. Is there a way to prevent this?

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47

1 Answers1

0

I can't say for certain without more context, but this may be a concurrency problem. List is not thread safe. Try using ConcurrentBag<T> instead of List<T>.

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80