C# update variable in thread

I am learning threading in C#, and I have a problem :

I have a list of items, and each item refreshes the value of one variable every second, thanks to a DispatcherTimer. Then, I created a thread, with an infinite loop, and send this value.

Maybe the code will be better to understand.

Product :

public class Product : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void notifyPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    private double price;
    public double Price
    {
        get { return price; }
        set
        {
            price = value;
            notifyPropertyChanged("Price");
        }
    }

    private Timer timer;

    public Product(int time)
    {
        timer = new Timer(time);
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }

    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Random r = new Random();
        this.Price = Math.Round(r.NextDouble() * (maxPrice - minPrice) + minPrice, 2);
    }
}

Main :

public MainWindow()
{
    Thread thread;
    InitializeComponent();
    this.DataContext = this;

    thread = new Thread(() => createServer(listGroupProduct));
    thread.Start();
}

public static void createServer(ObservableCollection<GroupProducts> list)
{
    string client = "";
    try
    {
        IPAddress ipAdress = IPAddress.Parse("xxx.xxx.xx.xx");
        TcpListener listener = new TcpListener(ipAdress, 1220);

        listener.Start();
        socket = listener.AcceptSocket();

        while (true)
        {
            articlesString = list[0].Price.ToString();
            byte[] bytes = new byte[list.Count * 50];
            bytes = System.Text.Encoding.ASCII.GetBytes(articlesString.ToCharArray());

            socket.Send(bytes);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

My problem is : the value send is always the same, but if I check the value in the main, the value changed...

Have you a solution ?

Answers


Declare private double price; as private volatile double price; since it's used by multiple threads.

You might want to read: http://www.andrewdenhertog.com/c/thread-safe-lock-volatile-and-interlock-in-c/


Need Your Help

Select value in multiselect through c# code

c# html winforms webbrowser-control

guys! I have to set some fields values automatically through code in my win forms application, which contains a web browser. The only thing not working is setting value in multiselect. I can click