我有一个测量仪器,可以在指定时间内创建测量值。在此期间,我必须从内部存储器中取出测量值以防止溢出。 目前我有这个:
public int FetchDatalog(int Time_s, double Period, out int Count, ref double[] Results)
{
Count = 0;
try
{
DateTime timeout = DateTime.UtcNow.AddSeconds(Time_s);
double[] values;
while (DateTime.UtcNow < timeout)
{
values = //here is the command to tell the instrument to return 10 results
Count = values.Count();
Thread.Sleep(500);
//HERE IS SOMETHING MISSING <-----
}
}
return 0;
}
所以我有一个读取循环的函数总是10个仪器的结果,直到指定的时间结束。在循环期间,必须合并读取数据。
在箭头标记的位置,我现在需要将10个值合并在一起的东西,最后将所有合并的值返回到结果中。
我怎么能以未知的长度做到这一点?
(因为额外的问题是:10个结果可能是“最多10个”结果。有时少于10个,所以如果只需要读取1个值,我也可以在这里更改,但这会使它变得更慢。
感谢您的帮助
在这里添加了评论,因此它的可读性 - Sayse
我的意思是合并:
loop1: values[]=1,2,3,4,5,6,7,8,9,0;
loop2: values[]=11,22,33,44,55,66,77,88,99,11
loop3: values[]=111,222,333,444,555,666,777,888,999,111
这三个值最终应该在参数结果中返回
result[]=1,2,3,4,5,6,7,8,9,0,11,22,33,44,55,66,
77,88,99,11,111,222,333,444,555,666,777,888,999,111
所以他们应该把它们组合成一个更大的阵列。
答案 0 :(得分:1)
如果由于某种原因需要将数组维护为参数类型,可以只创建一个列表,附加到列表中,然后返回结果:
public int FetchDatalog(int Time_s, double Period, out int Count, ref double[] Results)
{
Count = 0;
List<double> existing = new List<double>(Results);
try
{
DateTime timeout = DateTime.UtcNow.AddSeconds(Time_s);
double[] values;
while (DateTime.UtcNow < timeout)
{
values = //here is the command to tell the instrument to return 10 results
Count += values.Length;
Thread.Sleep(500);
existing.AddRange(values);
}
}
finally
{
Results = existing.ToArray();
}
return 0;
}
如果我有我的druthers,它看起来更像是:
public int FetchDatalog(int readLength, double sleepPeriod, List<double> results)
{
var readingsCount = 0;
try
{
var timeout = DateTime.UtcNow.AddSeconds(readLength);
while (DateTime.UtcNow < timeout)
{
values = RetrieveBufferedSensorReadings(10);
readingsCount += values.Length;
results.AddRange(values);
Thread.Sleep(sleepPeriod);
}
return readingsCount;
}
catch (Exception e) //<-- this should be special purpose based on sleep/read failures
{
throw; //Return -1 or the like if you must... but ew.
}
}
您甚至可以查看使用4.0中较新的async
功能,因为Thread.Sleep
通常被认为是错误的。
修改强>
根据您的上一条评论,您似乎正在这样做:
double[] Results = new double[100];
ret = GetData(TimeSec, out Count, ref Results);
我觉得这是一个糟糕的结构,但我们会把它作为一种学习工具:
public int GetData(int Time_s, out int Count, ref double[] Results)
{
var lengthIncrement = 100;
Count = 0;
try
{
DateTime timeout = DateTime.UtcNow.AddSeconds(Time_s);
double[] values;
while (DateTime.UtcNow < timeout)
{
values = //here is the command to tell the instrument to return 10 results
//Before copying over value, make sure we won't overflow
//If we will, extend array
if (Count + values.Length > Results.Length) {
var temp = new double[Results.Length + lengthIncrement];
Array.Copy(Results, temp, Count);
Results = temp;
}
Array.Copy(values, 0, Results, Count, values.Length);
Count += values.Length;
Thread.Sleep(500);
}
}
return 0;
}
请允许我重申许多其他人所说的......以下是一个更好的设计:
var results = new List<double>();
ret = GetData(TimeSec, out Count, results);