Click here to Skip to main content
15,916,835 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
       private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 1000000; i++)
            {
                label1.Text = i.ToString();
            }
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label1.Text = 0.ToString();
        }</pre

After i press button1, i is increasing and button2 is Locked until i is finished.
how can i press button2 at anytime?

What I have tried:

<pre>      private void button1_Click(object sender, EventArgs e)
        {
            Thread th1 = new Thread(Increment);
            th1.Start();
           
        }
        private void Increment()
        {
            for (int i = 0; i < 10000; i++)
            {
                label1.Text = i.ToString();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            reset();
        }
        private void reset()
        {
            label1.Text = 0.ToString();
        }
Posted
Updated 7-Nov-17 15:31pm
v3
Comments
EZW 7-Nov-17 21:06pm    
Maybe have the function for button one in a thread?

You can't. You have the UI thread tied up doing all of the work in the button1 handler. Until that method returns, the UI cannot repaint itself (that's why your label doesn't show a value when you change it) and cannot respond to mouse and key events.

You have to move the long running code in the button handler to a background thread. That catch is that thread will NOT be able to directly update the label control itself. You have to Invoke a method on the UI thread and pass the value you want the label to show. This method you invoke will then update the label with the new value.

Read this: How to: Make Thread-Safe Calls to Windows Forms Controls | Microsoft Docs[^]
 
Share this answer
 
Hello,
this problem was interesting to me when I was learning C#, and here is my solution :

MainForm.cs
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace Buttons_and_Threading
{
	/// <summary>
	/// Description of MainForm.
	/// Program code below needs two buttons and one label
	/// Initial buttons fore color should be set to green
	/// it needs .net framework 4.0 to run perfectly
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			//
			// The InitializeComponent() call 
			// is required for Windows Forms designer support.
			//
			InitializeComponent();
		}
		
		#region-   Parallel process methods and variables   -
		
		Thread Parallel;
		int i;
		
		protected delegate void Refresh_Data(string Text);
		
		void Button_1()
		{
			for (i = 0; i < 1000000; i++)
			{
				
				if(label1.InvokeRequired)
				{
					Refresh_Data refresh = Refresh_Label_1_Text;
					Invoke(refresh,i.ToString());
				}
				
			}
		}
		
		void Initialize_and_Start_New_Thread()
		{
			Parallel = new Thread(Button_1);
			Parallel.Start();
		}
		
		void Stop_Thread()
		{
			Parallel.Abort();
			while(Parallel.ThreadState != ThreadState.Aborted)
			{
				
			}
		}
		
		void Refresh_Label_1_Text(string Text)
		{
			label1.Text = Text;
		}
		
		void MainFormFormClosing(object sender, 
		                         System.Windows.Forms.FormClosingEventArgs e)
		{
			//
			// Before closing program check does parallel thread is
			// still running and stop it
			//
			
			if(Parallel.ThreadState != ThreadState.Aborted)
			{
				Parallel.Abort();
				while(Parallel.ThreadState != ThreadState.Aborted)
				{
					//
					// do nothing until parallel thread is stopped
					//
				}
			}
		}
		#endregion
		
		void Button1Click(object sender, EventArgs e)
		{
			if(button1.ForeColor == Color.ForestGreen)
			{
				//
				// change button text collor to red and 
				// start new parallel thread
				//
				button1.ForeColor = Color.Red;
				Initialize_and_Start_New_Thread();
			}
			else
			{
				//
				// Stop parallel thread and
				// change button text collor to green
				//
				Stop_Thread();
				button1.ForeColor = Color.ForestGreen;
			}
		}
		
		void Button2Click(object sender, EventArgs e)
		{
			//
			// reset counter to zero and
			// update label 1 text
			//
			i=0;
			if(label1.InvokeRequired)
			{
				Refresh_Data refresh = Refresh_Label_1_Text;
				Invoke(refresh,i.ToString());
			}
			
			else
				Refresh_Label_1_Text(i.ToString());
		}
	}
}



Main.Form.Designer.cs
namespace Buttons_and_Threading
{
	partial class MainForm
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;
		
		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}
		
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			this.button1 = new System.Windows.Forms.Button();
			this.button2 = new System.Windows.Forms.Button();
			this.label1 = new System.Windows.Forms.Label();
			this.SuspendLayout();
			// 
			// button1
			// 
			this.button1.ForeColor = System.Drawing.Color.ForestGreen;
			this.button1.Location = new System.Drawing.Point(14, 18);
			this.button1.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(264, 38);
			this.button1.TabIndex = 0;
			this.button1.Text = "Button 1";
			this.button1.UseVisualStyleBackColor = false;
			this.button1.Click += new System.EventHandler(this.Button1Click);
			// 
			// button2
			// 
			this.button2.ForeColor = System.Drawing.Color.ForestGreen;
			this.button2.Location = new System.Drawing.Point(14, 64);
			this.button2.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
			this.button2.Name = "button2";
			this.button2.Size = new System.Drawing.Size(264, 38);
			this.button2.TabIndex = 1;
			this.button2.Text = "Button 2";
			this.button2.UseVisualStyleBackColor = false;
			this.button2.Click += new System.EventHandler(this.Button2Click);
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(20, 127);
			this.label1.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(158, 29);
			this.label1.TabIndex = 2;
			this.label1.Text = "Label 1";
			// 
			// MainForm
			// 
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
			this.ClientSize = new System.Drawing.Size(292, 171);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.button2);
			this.Controls.Add(this.button1);
			this.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
			this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
			this.MaximizeBox = false;
			this.MaximumSize = new System.Drawing.Size(300, 200);
			this.MinimizeBox = false;
			this.Name = "MainForm";
			this.Text = "Buttons and Threading";
			this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainFormFormClosing);
			this.ResumeLayout(false);
		}
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button button2;
		private System.Windows.Forms.Button button1;
	}
}


Try to learn how to work with Delegates, codeproject has many articles on that subject.

All the best,
Željko Perić
 
Share this answer
 
v3
Yes, you need threading, and the simplest way to use it is with the 'BackgroundWorker. CodeProject is your friend: [^], [^], [^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900