Can anyone PLEASE explain this behavior
I am providing code below... but this is what is happening!
I am setting an application, and I have a timer that fires every 100 msec. My application creates a new thread and it generates a random number, assigns it to a variable, sleeps 70msec then dies. I am not disabling/enabling the timer every time the event occurs.... So, I decided to change the timer's interval to 30msec, and I expected either the application to crash or my PC to get stuck... but my application is running, and it hasn't crashed yet. WHY I can't find anything logical in this (but that could be due to my limited knowledge of UI programming, as well as threading).
Please see code for more details.Can anyone please help me understand what is actually happening and why is my application still running
The code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using System.Collections;
namespace TestApp
{
public partial class Form1 : Form
{
Thread t1 = null;
string str1;
Random r = new Random();
//
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
public void Test1000()
{
str1 = r.Next().ToString();// SP1.ReadLine();
Thread.Sleep(70);
}
// timer interval was set to 30 in the Form Designer
private void timer1_Tick(object sender, EventArgs e)
{
try
{
t1 = new Thread(new ThreadStart(Test1000));
t1.Start();
while (t1.IsAlive)
Thread.Sleep(10); // keep checking if the thread is still alive.
label1.Text = str1; //update the random number generated in the thread.
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
//
Thread.Sleep(100);
GC.Collect();
}
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
if (t1 != null)
t1.Abort();
//
label1.Text = "";
this.Close();
}
}
}