在一段时间内不断请求和收集数据

时间:2016-01-04 17:08:44

标签: c# loops datetime time constants

我需要通过发送命令然后读取结果,在X分钟内连续检索数据。我不确定以下代码是否有效或是为了不断检索:

DateTime utcStartTime = DateTime.UtcNow;
        while (DateTime.UtcNow <= (utcStartTime.AddSeconds(recordTime)))                       //Run the read-write function for approximately the time specified
        {
            try
            {

                Write("Write.Request");                                 //Requests the data
                Pmeas = Read();                                         //Reads the returned string. String = "ReadError" if no result is found.
                                                                        //Note that the following error checker doesn't effect the speed of data collection at a millisecond level (already checked), and is therefore not the cause of any delay.
                if (String.IsNullOrEmpty(Pmeas))
                {
                    Pmeas = "ReadError";                                //Necessary due to an apparent overwrite caused by the read function - Tells the later output (outside of while loop) that Pmeas experienced a read error
                    DateTime utcTime = DateTime.UtcNow;                 //Get the current time in UTC seconds (may need correcting).
                    pArray[i] = (Pmeas + "\t" + utcTime.ToString("%d") + Environment.NewLine);    //Appends the Pmeas of each instance to a string array with a timestamp
                }
                else
                {
                    DateTime utcTime = DateTime.UtcNow;
                    pArray[i] = (Pmeas + "\t" + utcTime.ToString("%d") + Environment.NewLine);    //Appends the Pmeas of each instance to a string array with a timestamp
                }
                Pmeas = "ReadError";                                    //Reset Pmeas to prove in file that Pmeas experienced a read error
            }
            catch (Exception f)                                         //Catch an exception if try fails
            {
                Console.WriteLine("{0} Exception caught.", f);
            }
            i++;                                            //let i grow so that the array can also grow, plus have a variable already available for being having the string being written into a file (not part of question or code-in-question).
        }

请注意,所有变量(如i,Pmeas和pArray)都是在循环之前预定义的(以防止错误),UTC应该以秒为单位(不确定当前语法;具有小数精度)。正如我所说的,我正在寻找一种方法,该方法使用上面给出的读写功能不断地从另一个源收集数据,并在一段时间内不间断地持续这样做。我的简单问题是, 这是收集数据的正确方法,还是有更好和/或更有效的方法?

欢迎代码上的所有输入,即使它没有完整回答问题。

1 个答案:

答案 0 :(得分:1)

字符串连接可能很慢,尝试创建一个包含DateTime和字符串的类,并让pArray保持该字符串。稍后在时间不重要时转换为字符串。还可以使用秒表记录持续时间,DateTime的最小分辨率约为15ms。

//Declared elsewhere
public class DataPoint
{
    public TimeSpan Time {get; set;}
    public String Message {get; set;}
}


    List<DataPoint> dataPoints = new List<DataPoint>(pArray.Length); //make the default size the same as pArray so we don't waist time growing the list.

    Stopwatch duration = new Stopwatch();
    DateTime utcStartTime = DateTime.UtcNow;
    duration.Start();
    DateTime endTime = utcStartTime.AddSeconds(recordTime); //Move this out of the loop so it only does the calculation once.
    while (DateTime.UtcNow <= endTime)                       //Run the read-write function for approximately the time specified
    {
        try
        {

            Write("Write.Request");                                 //Requests the data
            Pmeas = Read();                                         //Reads the returned string. String = "ReadError" if no result is found.

            var dataPoint = new DataPoint
                {
                    Time = duration.Elapsed,
                    Message = Pmeas
                };
            dataPoints.Add(dataPoint);                                                     
            Pmeas = "ReadError";                                    //Reset Pmeas to prove in file that Pmeas experienced a read error
        }
        catch (Exception f)                                         //Catch an exception if try fails
        {
            Console.WriteLine("{0} Exception caught.", f);
        }
    }

    //Now that we are out of the time critical section do the slow work of formatting the data.
    foreach(var dataPoint in dataPoints)
    {
        var message = dataPoint.Message;
        if (String.IsNullOrEmpty(message))
        {
            message = "ReadError";
        }
        pArray[i] = message + "\t" + (utcStartTime + dataPoint.Time).ToString("%d") + Environment.NewLine;    //Appends the Pmeas of each instance to a string array with a timestamp

        i++;                                            //let i grow so that the array can also grow, plus have a variable already available for being having the string being written into a file (not part of question or code-in-question).
    }

然而,这可能是一个微小的变化,获得一个分析器(visual studio comes with one,但我喜欢使用DotTrace),看看实际花费的时间最多,并集中精力。