由于另一个线程,WPF DataGrd未正确刷新
我正在开发一个绑定到DataGrid的WPF应用程序,如下所示:由于另一个线程,WPF DataGrd未正确刷新,wpf,multithreading,datagrid,Wpf,Multithreading,Datagrid,我正在开发一个绑定到DataGrid的WPF应用程序,如下所示: <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Source={StaticResource tradeViewModel}, Path=Result}" public static class TradePriceChanger { static List<
<DataGrid AutoGenerateColumns="True"
ItemsSource="{Binding Source={StaticResource tradeViewModel},
Path=Result}"
public static class TradePriceChanger
{
static List<Trade> tradeList = new List<Trade>();
static int TradeCounter = 1;
static ManualResetEvent manualReset = new ManualResetEvent(false);
public static IEnumerable<Trade> GetTrades()
{
Thread t1 = new Thread(new ThreadStart(One));
t1.Start();
Thread t2 = new Thread(new ThreadStart(Two));
t2.Start();
manualReset.WaitOne();
return tradeList;
}
public static void One()
{
for (int i = 1; i < 10; i++)
{
tradeList.Add(new Trade ( "One" + i, i ));
}
Interlocked.Decrement(ref TradeCounter);
if (TradeCounter == 0)
manualReset.Set();
}
public static void Two()
{
for (int i = 1; i < 10; i++)
{
tradeList.Add(new Trade("Two" + i, i));
}
Interlocked.Decrement(ref TradeCounter);
if (TradeCounter == 0)
manualReset.Set();
}
}
交易类有一个计时器,每1秒将其价格更新为一个随机值
public class Trade:INotifyPropertyChanged
{
private string _name;
private double _price;
public Trade(string name, double price)
{
_name = name;
_price = price;
TimerCallback callback = new TimerCallback(ChangePrice);
Timer timer = new Timer(callback, this, 0, 1000);
}
private static void ChangePrice(object obj)
{
if (obj is Trade)
{
Trade trade = obj as Trade;
trade.Price = trade.Price + ( new Random().Next(-1,2) * (new Random().NextDouble()));
}
}
public string Name { get { return _name; } set { _name = value; } }
public double Price
{
get
{
return _price;
}
set
{
_price = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Price"));
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
现在的问题是,当我在TradePriceChanger.GetTrades()中仅运行线程t1时,网格中的值正在正确刷新。但是,如果我同时运行这两个命令,UI上就不会发生刷新
我是不是遗漏了什么
请让我知道
谢谢,
Mahesh使用“
manualReset.WaitOne()”似乎只在等待一个线程代码>,但如果希望两个线程都有时间执行,则应使用WaitAll()代码>否则一个线程可以完成,函数将退出,因为等待将得到满足
您似乎正在添加到交易列表,而没有任何线程同步,因此两个线程都可以写入此列表,并导致列表中的状态不一致Mahesh是否打算更改静态int TradeCounter=1;到静态int TradeCounter=2??