private void TransferItem() { while (true) { int item; lock (_lockObj) { if (FirstItems.Count == 0) { break; } int n = new Random(unchecked ((int)DateTime.Now.Ticks)).Next(0, FirstItems.Count);//随机抽取出一项 item = FirstItems[n]; //在UI线程上同步执行,否则可能出现索引越界(会阻塞UI线程,在其中加入sleep可以很明显看出来) UIDispatcherHelper.CheckInvokeOnUI(() => { FirstItems.RemoveAt(n); //Thread.Sleep(100); }); } UIDispatcherHelper.CheckBeginInvokeOnUI(() => { SecondItems.Add(item); }); Thread.Sleep(100); } }
private void InitLists() { FirstItems.Clear(); SecondItems.Clear(); FirstItems = new ObservableCollection <int>(Enumerable.Range(0, 30).OrderBy(x => Guid.NewGuid()));//生成一系列整数 }