如何从调度程序计时器生成历史数组?C#
基本上,我必须制作一个调度程序计时器,在数组计数时将变量存储在数组中,然后在单击rawDataButton时在文本框中显示历史数组。出于某种原因,我的数组只显示最近的数组,从不在数组中存储,下面是我的代码如何从调度程序计时器生成历史数组?C#,c#,arrays,xaml,uwp,dispatchertimer,C#,Arrays,Xaml,Uwp,Dispatchertimer,基本上,我必须制作一个调度程序计时器,在数组计数时将变量存储在数组中,然后在单击rawDataButton时在文本框中显示历史数组。出于某种原因,我的数组只显示最近的数组,从不在数组中存储,下面是我的代码 DispatcherTimer timer = new DispatcherTimer(); MeasureLengthDevice dg = new MeasureLengthDevice(); int mostRecnet = 0; int[] arr = new int[10]; pr
DispatcherTimer timer = new DispatcherTimer();
MeasureLengthDevice dg = new MeasureLengthDevice();
int mostRecnet = 0;
int[] arr = new int[10];
private void StartCollectingDataButton_Click(object sender, RoutedEventArgs e)
{
timer.Interval = new TimeSpan(0, 0, 1);
timer.Start();
timer.Tick += timer_Tick;
}
private void timer_Tick(object sender, object e)
{
mostRecnet = dg.GetMeasurement();
recentDataTextBlock.Text = mostRecnet.ToString();
for(int i = 0; i < arr.Length; i++)
{
arr[i] = mostRecnet;
}
}
private void stopCollectingDataButton_Click(object sender, RoutedEventArgs e)
{
timer.Stop();
}
private void rawDataButton_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < arr.Length; i++)
{
mostRecnet = arr[i];
rawDataTextBox.Text += arr[i].ToString() + "\n";
}
}
dispatchermer timer=newdispatchermer();
MeasureLength设备dg=新的MeasureLength设备();
int mostRecnet=0;
int[]arr=新的int[10];
private void StartCollectingDataButton_Click(对象发送方,RoutedEventTargets e)
{
timer.Interval=新的时间跨度(0,0,1);
timer.Start();
timer.Tick+=定时器_Tick;
}
私有无效计时器(对象发送方,对象e)
{
mostRecnet=dg.GetMeasurement();
recentDataTextBlock.Text=mostRecnet.ToString();
对于(int i=0;i
您可以替换
int mostRecnet = 0;
int[] arr = new int[10];
需要使用列表和一些基本互斥代码手动计数:
//Always use a dedicated object to lock onto
private object mutex = new object();
var History = new List<int>();
当你读出来的时候,你会这样做:
lock(mutex){
History.Add(mostRecent);
}
lock(mutex){
//do whatever you need to output the list contents
}
请注意,锁定输出将阻止tick事件的处理。尤其是批量写入UI可能需要相当长的时间,只需10-100毫秒。您可以替换
int mostRecnet = 0;
int[] arr = new int[10];
需要使用列表和一些基本互斥代码手动计数:
//Always use a dedicated object to lock onto
private object mutex = new object();
var History = new List<int>();
当你读出来的时候,你会这样做:
lock(mutex){
History.Add(mostRecent);
}
lock(mutex){
//do whatever you need to output the list contents
}
请注意,锁定输出将阻止tick事件的处理。尤其是对UI的批量写入可能需要相当长的时间,很容易在10-100毫秒内完成。看起来您正在使用一个度量来填充数组的所有元素。您可能希望使用
列表,而不是数组。无需手动组织阵列。当然,使用Dispatcher计时器可能会出现并发性问题。并且并发列表不存在。因为你只需要在事后阅读列表,这可能不是什么大问题。@ChiefTwoPencils是的,我在调试后也注意到了这一点,但我正试图在数组中存储最新的内容。就像另一个人说的,列表会更好。看起来您正在使用单个度量填充数组的所有元素。您可能希望使用列表
,而不是数组。无需手动组织阵列。当然,使用Dispatcher计时器可能会出现并发性问题。并且并发列表不存在。因为你只需要在事后阅读列表,这可能不是什么大问题。@ChiefTwoPencils是的,我在调试后也注意到了这一点,但我正试图在数组中存储最新的内容。就像另一个人所说的,列表会更好。将lock
与Dispatcher一起使用简直是胡说八道。勾号处理程序已经在UI线程中运行,并且根本没有并发问题。将lock
与Dispatcher一起使用简直是胡说八道。勾号处理程序已经在UI线程中运行,并且根本没有并发问题。