How to separate UI thread and process thread, in Windows Forms

360 Views Asked by At

I develop Forms Application using C# to collect data from a spectrometer device. When I set continuous acquisition, I am not able to perform other operations with UI during the acquisition happens. I am thinking to use multithreading. I am from Science background and not much familiar with C#. Kindly help me with some code also.

Please see part of code which has a button click to start acquisition and another button to save the acquired data. I want to save data, in between acquisition happens.

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 !!");
            
        }
1

There are 1 best solutions below

0
On

If you are not familiar with multithreading, you can start by using a BackgroundWorker as it provides events to update the UI easily.

So your button will start the worker and periodically the worker will call ReportProgress to update the UI

my favorite ressource related to threading http://www.albahari.com/threading/