我正在学习C#中的线程,我遇到了一个问题:
我有一个项目列表,每个项目每秒刷新一个变量的值,这要归功于DispatcherTimer
。
然后,我创建了一个带有无限循环的线程,并发送该值。
也许代码会更好理解。
产品:
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);
}
}
主要:
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);
}
}
我的问题是:值send始终是相同的,但如果我检查main中的值,则值已更改...
有解决方案吗?
答案 0 :(得分:1)
将private double price;
声明为private volatile double price;
,因为它被多个线程使用。
您可能需要阅读:http://www.andrewdenhertog.com/c/thread-safe-lock-volatile-and-interlock-in-c/