Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6331571
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T18:05:42+00:00 2026-05-24T18:05:42+00:00

I am doing a practise GUI Oven program using a thread, I am not

  • 0

I am doing a practise GUI Oven program using a thread, I am not sure if I should even be doing this because I want to interact with the GUI when the Heating process is ongoing. When I try to abort the thread by click btnStop_Click, it throws the NullReference exception:

System.NullReferenceException: Object reference not set to an instance of an object.

Please advice on how can I gracefully stop the thread. Thanks.

Code:

 public partial class Form1 : Form
        {
            private Thread t;

            public Form1()
            {
                InitializeComponent();
            }
            // button to begin heating
            private void btnStart_Click(object sender, EventArgs e)
            {   
                if ((txtMin.Text) == "" || (txtSec.Text) == "")
                {
                    MessageBox.Show("Please enter duration of heating");
                }
                else
                {
                    t = new Thread(heatIt);
                    btnHeat.Enabled = false;
                    t.Start();
                }
            }

           //stop heating
            private void btnStop_Click(object sender, EventArgs e)
            {
                Heating heat = new Heating();
                Form1 l = new Form1();
                l.Subscribe(heat);
                heat.stopHeat();
                btnHeat.Enabled = true;
            }

            private void heatIt()
            {
            // heat food Implementation that calls the 'Heating' class
            }

           public void Subscribe(Heating m)
           {
            m.heatComplete += SignalHeatCompleted;
            m.heatStop += SignalStop;
           }

           private void SignalHeatCompleted(Heating m, EventArgs e)
           {
            MessageBox.Show( "Done, please enjoy your food");
            return;
           }

           private void SignalStop(Heating m, EventArgs e)
           {
           t.Abort();
            MessageBox.Show("Heating Terminated");
            return;            
           }

public class Heating
        {
            public event HeatingCompleted heatComplete; // Heating Completed Event
            public event HeatingStop heatStop;          // Heating Stop Event
            public EventArgs e = null;
            public delegate void HeatingCompleted(Heating h, EventArgs e);
            public delegate void HeatingStop(Heating s, EventArgs e);

            public void startHeat(int temp, int min, int sec)
            {
                int totalSec;
                totalSec = ((min*60) + sec) * 1000;

                Thread.Sleep(totalSec);
                if (heatComplete != null)
                {
                    heatComplete(this, e);
                }
                else
                {
                    //Use default signal if there's no subscription to this event
                    MessageBox.Show("*TING*");

                }
                return;    
            }

            public void stopHeat()
            {
                if (heatStop != null)
                {
                    heatStop(this, e);
                }
            }
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T18:05:44+00:00Added an answer on May 24, 2026 at 6:05 pm

    Several remarks:

    1. You should never use Thread.Abort to stop background tasks. This is a bad practice, as it forces aborting the background thread regardless of its state. Use a volatile bool flag instead, and check (every once in a while) if its value has changed.

    2. It seems that your Form represents a UI for business logic extracted into a separate class (Heating). In that case, it probably makes sense to have only a single instance per form, and put it in a private field. Right now you are creating a new instance inside your Stop method, which is probably wrong (since I presume you already use it in the heatIt method).

    3. For each Subscribe method, try to keep a habit of adding a Unsubscribe method, which detaches event handlers at some point. This way GC can collect your listeners after they are no longer needed, and you prevent adding the same event handlers several times.

    I would expect something like:

    private Heating _heating;
    private Thread _workerThread;
    private volatile bool _stopRequest = false;
    
    void Start_Btn_Pressed(object sender, EventArgs e)
    {
        // create the private instance
        _heating = new Heating();
        Subscribe(_heating);
    
        // start the thread
        _stopRequest = false;
        _workerThread = new Thread(HeatIt);
        _workerThread.Start();
    }
    
    void Stop_Btn_Pressed(object sender, EventArgs e)
    {
        // request stop
        _stopRequest = true;
    
        // wait until thread is finished
        _workerThread.Join();
    
        // unsubscribe
        // ** note that a better place for unsubscribing 
        //    might be at the end of the HeatIt method
        Unsubscribe(_heating);
    }
    

    And, in your background worker method, you will need to have a loop which checks if _stopRequest has been set:

    void HeatIt()
    {
        while (!_stopRequest && !finishedWork)
        {
            // do work
        }
    }
    

    Note that you must have a place in your worker method which will check the _stopRequest flag. Otherwise the only way to stop it is to Abort it (like you did), which is not recommended.

    Apart from that, you don’t need to stop the thread (like you did in your SignalStop method) once the process is finished. When HeatIt method returns (ends), the thread will also end, and there is no need to do this.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Just looking for the best practise way of doing this. I have a table
Doing odd/even styling with jQuery is pretty easy: $(function() { $(.oddeven tbody tr:odd).addClass(odd); $(.oddeven
Doing an ajax get request works as expected using the following code: $.ajax({ type:
Doing a some practice questions for exam tomorrow can't figure out this one What
I'm currently doing some GUI testing on a ASP.net 2.0 application. The RDBMS is
I am making a Gui Library on top of SDL using C++. (Don't ask
I'm not a solid GUI programmer, so I'm trying to understand different event architectures.
I'm doing simple GUI updates on a timer. Which method is better to use
I am currently studying Web Services and after doing a sample practise in a
This might be a silly question but whats the best practise for getting a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.