【发布时间】:2021-05-19 03:28:30
【问题描述】:
我使用 C# 开发表单应用程序以从光谱仪设备收集数据。当我设置连续采集时,在采集期间我无法使用 UI 执行其他操作。我正在考虑使用多线程。我来自科学背景,对 C# 不太熟悉。请帮我写一些代码。
请查看部分代码,其中有一个按钮单击开始采集,另一个按钮保存采集的数据。我想在采集之间保存数据。
private void button2_Click(object sender, EventArgs e)
{
while (true)
{
this.Refresh();
int numberOfPixels; // number of CCD elements
double[] spectrum;
spectrum = null; // spectrometerIndex = 0;
if (spectrometerIndex == -1)
return; // no available spectrometer
numberOfPixels = wrapper.getNumberOfPixels(spectrometerIndex);
wrapper.setBoxcarWidth(spectrometerIndex, 0);
wrapper.setCorrectForElectricalDark(spectrometerIndex, 1);
wrapper.setIntegrationTime(spectrometerIndex, 1000); // acquisition time in microsecs
int acquiretime = 100;
if (textBoxin.Text != "")
{
int.TryParse(textBoxin.Text, out acquiretime); //arbitrary acquiretime
}
Stopwatch integrate = new Stopwatch();
integrate.Start();
while (integrate.Elapsed < TimeSpan.FromMilliseconds(acquiretime))
{
this.Refresh();
spectrum = (double[])wrapper.getSpectrum(spectrometerIndex); data from spectrometer
}
integrate.Stop();
}
}
private void button7_Click(object sender, EventArgs e)
{
File.WriteAllText((@"D:\ExecRonefile\abcd.csv"), csv.ToString());
MessageBox.Show("Data saved into csv format succesfully !!");
}
【问题讨论】:
-
这段代码不完整,无法编译。如果没有您发布真实代码,我无法提出改进建议 - 最好是 minimal reproducible example。请您阅读How to Ask,然后改进您的问题?
-
多线程是正确的方法。但这是一个庞大而复杂的主题,无法在这里提供一个很好的概述。我建议阅读async/await、tasks 和best practices。阅读有关多线程的一些常见危害也很有用。
标签: c# multithreading winforms data-acquisition