如何继续写入文件,直到停止方法被调用

本文关键字:方法 调用 文件 何继续 继续 | 更新日期: 2023-09-27 18:14:23

我有一个方法,从设备读取数据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和stop。当调用start时,它继续从设备读取数据并将其写入文件。当调用stop时,它将结束一切。我想做类似下面的事情,但确保不是阻塞,它停止写入时,停止被调用。我怎样才能正确地做这件事呢?我需要一个单独的威胁吗?

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);
}

如何继续写入文件,直到停止方法被调用

使用TPL执行如下操作:

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();
    }
}

下面是使用方法:

Worker worker = new Worker();
worker.Start();
//Do something here
//After a while
worker.Stop();

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