0

I have a program that run in a loop. it's this

private void ReadCamAuto_Click(object sender, EventArgs e)
{
    this.serialPort1.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.DataReceivedHandler);
    RunReadCamAuto = true;
    while (RunReadCamAuto)
    {
        serialPort1.WriteLine("2,2,2,2");
        CreatePic(4, 4);
    }
    this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.DataReceivedHandler);
}

but the problem is then I'm in the While loop I cant press any other Button in my program so it is not possible to stop. I have no idea how to stop it ?

I tried to press a button who set the RunReadCamAuto to false and Console.ReadKey()

I'm Using:

  • c# Form App

  • MS VS 2010

Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
LFS96
  • 856
  • 1
  • 12
  • 23

1 Answers1

3

You cannot expect user interface to work while the main thread is busy doing some work in a loop. Use BackgroundWorker object to fire desired loop in it - it's automatically invoked on other thread and from your main thread you can easily send the message to stop its work.

You need to assign your method to BackgroundWorker's DoWork event and then from your form just call myBackgroundWorker.RunWorkerAsync(). Then by calling myBackgroundWorker.CancelAsync() you will change its CancellationPending property to true, which you can be constantly checking in your loop to break execution.

Please see here.

Tarec
  • 3,268
  • 4
  • 30
  • 47