如何在调用stop方法之前继续写入文件

时间:2015-09-24 20:49:52

标签: c# multithreading io

我有一种方法,可以从设备读取数据5秒钟,然后将其写入二进制文件。

// Start acquisition
    try
    {
       // create file stream
       using (FileStream fileStream = new FileStream(filename, FileMode.Create))
       {
          using (BinaryWriter writer = new BinaryWriter(fileStream))
          {
              // start acquisition thread
       deviceManagerObj.StartAcquisition(deviceManagerObj.deviceConfigurations);

             // to stop the application after a specified time, get start time
             DateTime startTime = DateTime.Now;
             DateTime stopTime = startTime.AddSeconds(numSecondsRunning);


             // this is the data processing thread; data received from the devices will be written out to a file here
             while (DateTime.Now < stopTime)
             {
                float[] data = deviceManagerObj.ReadData(numValuesAtOnce);

                // write data to file
                for (int i = 0; i < data.Length; i++)
                    writer.Write(data[i]);
             }
          }
        }
  }
catch (Exception ex)
{
   Console.WriteLine("\t{0}", ex.Message);
}
finally
{
   // stop data acquisition
   deviceManagerObj.StopAcquisition();

   Console.WriteLine("Press any key exit...");
   Console.ReadKey(true);
}

我想在两个方面打破这个方法:开始和停止。调用start时,它会不断从设备读取数据并将其写入文件。当停止被调用时,它完成所有事情。我想做类似以下的事情,但确保不会阻塞,并且在调用停止时停止写入。我该怎么做呢?我需要一个单独的威胁吗?

public void start() {
   try
   {
        // create file stream
        using (FileStream fileStream = new FileStream(filename, FileMode.Create))
        {
           using (BinaryWriter writer = new BinaryWriter(fileStream))
           {
               // start acquisition thread\
       deviceManagerObj.StartAcquisition(deviceManagerObj.deviceConfigurations);
               // this is the data processing thread; data received from the devices will be written out to a file here
                while (true???) // I dont know how to do this
                {
                float[] data = deviceManagerObj.ReadData(numValuesAtOnce);

                // write data to file
                for (int i = 0; i < data.Length; i++)
                    writer.Write(data[i]);
        }
      }
   }
}

public void stop()
{
    // stop data acquisition
    deviceManagerObj.StopAcquisition();

    Console.WriteLine("Press any key exit...");
    Console.ReadKey(true);
}

1 个答案:

答案 0 :(得分:1)

使用TPL执行以下操作:

                gamma  omega
alpha beta              
A     1        22      3
      1        44      3
      2        66      3
B     3        88      3
      3       110      3
      4       132      3

在这里你是如何使用它的:

public class Worker
{
    private CancellationTokenSource m_CancellationTokenSource;

    public void Start()
    {

        m_CancellationTokenSource = new CancellationTokenSource();

        var token = m_CancellationTokenSource.Token;

        Task.Factory.StartNew(() =>
        {

            //Prepare the things you need to do before the loop, like opening the files and devices

            while (!token.IsCancellationRequested)
            {
                //Do something here like continuously reading and writing

            }

        }, token)
        .ContinueWith(t =>
        {
            //This will run after stopping, close files and devices here
        });

    }

    public void Stop()
    {
        m_CancellationTokenSource.Cancel();
    }

}

请注意,Start方法会立即返回,因为它将在线程池中的另一个线程上运行。