0
我有一種方法可以從設備讀取數據5秒並將其寫入二進制文件。如何保持寫入文件,直到調用stop方法
// 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);
}
我想打破這兩種方法:啓動和停止。當啓動被調用時,它不斷從設備讀取數據並將其寫入文件。當停止被稱爲它完成一切。我想要做類似下面的事情,但是確保不會阻塞,並且在停止被調用時停止寫入。我怎樣才能正確地做到這一點?我需要單獨的威脅嗎?
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);
}