gpt4 book ai didi

c# - C++ 新手,想在 MFC 应用程序中创建后台线程

转载 作者:行者123 更新时间:2023-11-28 06:29:02 27 4
gpt4 key购买 nike

我查看了几个示例,但没有找到一种简单的方法来在我负责修改的现有 C++ MFC 应用程序中创建后台线程。

我看了这篇文章 --> Multithreading: Creating Worker Threads但是这段代码不是开箱即用的。由于我是 C++ 的新手,我需要更多解释,并且本文假定我没有使用 C++ 的经验。

我正在努力实现我在下面提供的 C# 示例中所做的工作...

此代码每分钟创建一个新文件,但在该分钟过去并创建另一个文件之前,可能会向该文件写入数百次。我将文件名基于日期和时间,因此每个文件名都是唯一的。有一个标题行包含来自一组波长的项目,并且被写入每个文件一次,而我要存储的数据的后续行被写入多次。这是传入的值 rawData。您可以假设数据是整数数组或类似数组。 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 线程函数是不相关的。要在 MFC 程序中复制计时器方法,您可以在任何 CWnd 派生类中调用 SetTimer,并在该类中为 WM_TIMER 添加消息处理程序。您的消息处理函数将被定期调用。

关于c# - C++ 新手,想在 MFC 应用程序中创建后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27970251/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com