using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); UpdateThread = new Thread(DoUpdate); UpdateThread.IsBackground = true; UpdateCounter = 0; } private void button1_Click(object sender, EventArgs e) { if (UpdateThread.ThreadState != ThreadState.Running) { UpdateThread.Start(); } } private void DoUpdate() { while (true) { if (false)// some condition like x = 4 { break; // breka out of the loop } if (this.InvokeRequired) { this.Invoke(UpdateInvoker); } UpdateCounter++; Thread.Sleep(10); } } private int _updateCounter; public int UpdateCounter { get { return _updateCounter; } private set { _updateCounter = value; } } private MethodInvoker _updateInvoker; public MethodInvoker UpdateInvoker { get { if (_updateInvoker == null) { _updateInvoker = new MethodInvoker(delegate() { label1.Text = UpdateCounter.ToString(); }); } return _updateInvoker; } } private Thread _updateThread; public Thread UpdateThread { get { return _updateThread; } private set { _updateThread = value; } } } }