0

I apologize for anything noobish I am about to write, but I am fairly new to multithreading in C#. I have a Windows Form from which I create a new thread:

private void btn_start_Click(object sender, EventArgs e)
    {
        IMU IMUobject = new IMU();
        Thread IMUThread = new Thread(IMUobject.Main);
        IMUThread.Start();
    }

The function that run in this thread is defined in another class (IMU). The problem is that I'm not able to stop IMUthread in another Windows Form method. In particular I want to stop the thread when I press a button on the form, but this doesn't work as the program tells me that I have a null reference:

 private void btn_saveoffset_Click(object sender, EventArgs e)
    {
        IMUThread.Abort();
    }

The null reference is IMUThread: this is strange because I have declared it as a private class in the Windows Form

private Thread IMUThread
    {
        get;
        set;
    }

Because of this I cannot call the Abort() method (yes, I know that I shouldn't use Abort, but at the moment I just need this to work).

Do you have any suggestions on how I can correctly stop IMUThread from that event function? And why do I have a null reference on an object that is declared at the beginning of the code?

Frinzi
  • 1
  • Of course it's null, IMUThread is not referencing any instance of a running thread! `Thread IMUThread = new Thread(IMUobject.Main);` this is local to the function it is called in! – Suraj S Jul 06 '17 at 14:22
  • Read about `CancellationTokenSource` and `CancellationToken`. – Sir Rufo Jul 06 '17 at 14:27
  • yeah, @SurajS is right, just do `IMUThread = new Thread(IMUobject.Main);` instead of `Thread IMUThread = new Thread(IMUobject.Main);` – Eddy Jul 06 '17 at 14:29
  • Avoid Thread.Abort (see https://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) – Andrew Skirrow Jul 06 '17 at 14:30
  • @SurajS you have absolutely right! Thanks to everyone who has answered, that was easy :D – Frinzi Jul 06 '17 at 14:45

0 Answers0