【发布时间】:2015-01-15 18:15:28
【问题描述】:
我浏览了一些示例,但没有找到一种简单的方法来在我负责修改的现有 C++ MFC 应用程序中创建后台线程。
我查看了这篇文章 --> Multithreading: Creating Worker Threads 但此代码不能开箱即用。由于我是 C++ 新手,我需要更多解释,本文假设我没有 C++ 经验。
我正在努力实现我在下面提供的 C# 示例中所做的工作...
此代码每分钟创建一个新文件,但在该分钟过去并创建另一个文件之前,可能会写入该文件数百次。我将文件名基于日期和时间,因此每个文件名都是唯一的。有一个标题行包含来自波长数组的项目,并且写入每个文件一次,而我要存储的数据的后续行被写入多次。这是传入的值 rawData。您可以假设 data 是整数数组或类似数组。 ProcessHeader 每次创建文件时只发生一次。
private static double[] wavelengths;
private static System.Timers.Timer aTimer;
private static string fileNameAndPath = "";
private int count = 0;
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// Create a new file once a minute
fileNameAndPath = string.Format(@"C:\MyData_{0:yyyy-MM-dd_hh-mm-ss-tt}.csv", DateTime.Now);
var myFile = File.Create(fileNameAndPath);
myFile.Close();
}
private void ProcessHeader()
{
fileNameAndPath = string.Format(@"C:\Data_{0:yyyy-MM-dd_hh-mm-ss-tt}.csv", DateTime.Now);
var myFile = File.Create(fileNameAndPath);
myFile.Close();
string[] header = new string[] { string.Join(", ", wavelengths) };
File.AppendAllLines(fileNameAndPath, header);
}
private void ShowDateTimeAndCount()
{
// Open the file > add the date and time at the top > add a header row > add the data
File.AppendAllText(fileNameAndPath, String.Format("Run Date: {0}\tCount: {1}{2}", DateTime.Now.ToString(), ++count, Environment.NewLine));
}
private void LogData(double[] rawData)
{
// Create initial fileName
if (fileNameAndPath.Length == 0)
{
ProcessHeader();
}
ShowDateTimeAndCount();
// Detail row
string[] data = new string[] { string.Join(", ", rawData) };
File.AppendAllLines(fileNameAndPath, data);
}
////////////////////////////////////////////////////////////////////////
// Background Worker
////////////////////////////////////////////////////////////////////////
private void backgroundWorkerAcquisition_DoWork(object sender, DoWorkEventArgs e)
{
// BEGIN - run once a minute
aTimer = new System.Timers.Timer(60000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;
// END
}
这可以用 C++ MFC 完成吗?
【问题讨论】:
-
您似乎正在尝试使用 MFC 应用程序中提供的计时器。但是,我认为您需要准确解释您想要什么,而不是与您知道有效的代码进行比较。
-
代码添加了额外的细节。
标签: c# c++ multithreading mfc