increment the textbox using multithreading - c#

I want to create a C# form in which two text box show two different numbers.
After clicking on start button both numbers should start incrementing at same time should increment slowly so we can see them increment and clicking on stop button should stop increment.
Both text box are not related to each other any way.
public partial class Form1 : Form
{
Thread t1 = new Thread(new ThreadStart(increment1));
public static int fNumber = 0, sNumber = 0,flag = 0;
public Form1()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
t1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
}
private void number1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static void increment1()
{
Form1 frm = new Form1();
for (int i = fNumber;i<1000;i++)
{
frm.number1.Text = Convert.ToString(i);
}
}
}

public void Increment1()
{
for (int i = fNumber;i<1000;i++)
{
number1.Text = Convert.ToString(i);
number2.Text = Convert.ToString(i);
}
}
And just generally avoid static for threads. You can access your textboxes directly without the word this if you named your textboses number1 and number2. In a static method the variables need to be static aswell or you will get a compilation error.
For visibility, functions should have first letter in upper case. So you can distinguish them more easily from variables.

You are creating a new instance of Form1 which is wrong. Use the current Form1 that started the Thread.
Try
public partial class Form1 : Form
{
private Timer timer1;
public static int fNumber = 0, sNumber = 0,flag = 0;
public Form1()
{
timer1 = new Timer();
timer1.Interval = 1000;
timer1.Tick += timer1_Tick;
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void number1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
int i = 0;
int.TryParse(this.number1.Text, out i);
i++;
if(this.number1.InvokeRequired)
{
this.number1.BeginInvoke((MethodInvoker) delegate()
{
this.number1.Text = Convert.ToString(i);
});
}
else
{
this.number1.Text = Convert.ToString(i);
}
}
}
For safety measures, check if invoking is required.
Replace this.number1.Text = Convert.ToString(i); with this block of code.
if(this.number1.InvokeRequired)
{
this.number1.BeginInvoke((MethodInvoker) delegate()
{
this.number1.Text = Convert.ToString(i);
});
}
else
{
this.number1.Text = Convert.ToString(i);
}

Related

How to use a function from one form in another form?

I have several forms, but specifically I am trying to make the form1 do something whenever the timer in form5 ticks. When timer ticks, it should use the function SimulAuto in form1 to make it change. I start by using a click method to initiate form5. Ive tried several things but it just does not work. Or, can anyone help me by giving me an alternate approach to solving this problem. Thanks!
Here's my code:
public partial class FormPrincipal : Form
{
Point[] initialPos = new Point[100];
ListaVuelos lv = new ListaVuelos();//Declarar una lista de vuelos nueva.
Sector s = new Sector();
int MAX;
Form5 f5 = new Form5();
PictureBox[] aviones_vector = new PictureBox[100];//preguntar porque no me deja poner el integer MAX como referencia
public FormPrincipal()
{
InitializeComponent();
}
...
public void SimulAuto()
{
int minutos = f5.SetMinutos();
lv.Avanzar(minutos);
ActualizarPosicion();
}
private void automáticaToolStripMenuItem_Click(object sender, EventArgs e)
{
f5.ShowDialog();
}
}
public partial class Form5 : Form
{
int cuenta;
int tiempociclo;
int tiempototal;
public event Action SimulAuto;
public Form5()
{
InitializeComponent();
}
public int SetMinutos()
{
return this.tiempociclo;
}
private void Form5_Load(object sender, EventArgs e)
{
MessageBox.Show("Cada ciclo dura 5 segundos.");
timer1.Interval = 5000;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
tiempociclo = Convert.ToInt32(duracionCicloTxt.Text);
tiempototal = Convert.ToInt32(tiempoSimularTxt.Text);
cuenta = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
while ((cuenta*tiempociclo)<tiempototal)
{
cuenta++;
tiempoTranscurridoLbl.Text = "Tiempo transcurrido: " + Convert.ToString(((cuenta + cuenta) * tiempociclo)) + "minutos.";
}
MessageBox.Show("Simulación completada.");
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void button3_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void Form5_FormClosing(object sender, FormClosingEventArgs e)
{
cuenta = 0;
}
}

How to set a counter and increment 1 every 3 second and display it in label

private void timer3_Tick(object sender, EventArgs e)
{
}
Here is the full code to do that. Just add a Label named "label1" on your window.
public partial class Form1 : Form
{
private Timer timer3;
private int counter;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
counter = 0;
timer3 = new Timer();
timer3.Interval = 3000;
timer3.Tick += Timer3_Tick;
timer3.Start();
}
private void Timer3_Tick(object sender, EventArgs e)
{
counter++;
label1.Text = counter.ToString();
}
}

How to abort a while loop by clicking a button using C#

I have a function that displays numbers using a while loop but I want to stop execution of a while loop at random variable value using c# by clicking a button.
For Example:
private void FrqSent()
{
int i = 1;
while (i <= 5)
{
i = i + 1;
}
}
Here is a quick example on how you can use a Backgroundworker to accomplish your task:
public partial class Form1 : Form
{
private int i = 1;
public Form1()
{
InitializeComponent();
}
private void FrqSent()
{
while (i <= 500000000)
{
if (backgroundWorker1.CancellationPending)
{
break;
}
else
{
i = i + 1;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FrqSent();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(i.ToString());
}
}
Just create a new Windows-Forms Project and add a backgroundworker object aswell as 2 buttons. You have to set the DoWork, RunWorkerCompleted and Click events manually.
Edit: Do not forget to set the BackgroundWorker`s WorkerSupportsCancellation property to true.
not very elegant but simple
public partial class Form1 : Form
{
private bool _stop;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
_stop = false;
FrqSent();
}
private void buttonStop_Click(object sender, EventArgs e)
{
_stop = true;
}
private void FrqSent()
{
int i = 1;
while (i <= 5000000 && !_stop)
{
i = i + 1;
Application.DoEvents();
}
}
}

c#.net blocked when i work Background

My problem is that I want the form still display data when it increases but the form is blocked and I cannot do anything with it.
This is my code :
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
while (true)
for (int i = 1; i < 11; i++)
richTextBox1.Text += "here" + i + "/n";
}
}
}
How I can prevent form from blocking?
private void Form1_Load(object sender, EventArgs e)
{
BackgroundWorker BWorker = new BackgroundWorker();
BWorker.DoWork += BWorker_DoWork;
BWorker.RunWorkerAsync();
}
void BWorker_DoWork(object sender, DoWorkEventArgs e)
{
// while(true) is meaningless.
for (int i = 1; i < 11; i++)
{
Action UpdateUI = () => { richTextBox1.Text += "here" + i + "/n"; };
this.BeginInvoke(UpdateUI);
}
}
Split your working cycle into steps by utilizing timer
private int _workStep;
private void button1_Click(object sender, EventArgs e)
{
_workStep = 0;
timerWork.Start();
}
private void timerWork_Tick(...)
{
switch(workStep)
{
case 0:
... // do something
if(something)
_workStep = 1;
case laststep:
timerWork.Stop();
}
}
or put work into thread (by using Thread, BackgroundWorker or Task), but then you must use Invoke/BeginInvoke when updating something in the user interface (accessing controls).
You can do this to get a responsive ui
delegate void DisplayInvoker(string text);
private void DisplayinRichTextbox(string text)
{
if (this.InvokeRequired)
this.BeginInvoke(new DisplayInvoker(DisplayinRichTextbox), text);
return;
}
richTextBox1.Text += text;
}
private void button1_Click(object sender, EventArgs e)
{
// some synchronization would have to be done kill old
// pool threads when the button is hit again
//
ThreadPool.QueueUserWorkItem((x) =>
{
while (true)
for (int i = 1; i < 11; i++)
DisplayinRichTextbox("here" + i + "/n");
});
}

Text property not changing?

What is happening is, even though the questionNr is set to 1, it's not changing the .Text properties of ans1-4, as well as the questionLabel. Any help would be appreciated. Also as a sub-question, is it possible to do something along the lines of if(ans1.Clicked = true)?
public partial class Form1 : Form
{
int pointCounter = 0;
private SoundPlayer _soundPlayer;
int questionNr = 1;
public Form1()
{
InitializeComponent();
_soundPlayer = new SoundPlayer("song.wav");
}
private void pictureBox1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.amazon.com/Chuck-Seasons-One-Five-Blu-ray/dp/B007AFS0N2");
}
private void Form1_Load(object sender, EventArgs e)
{
_soundPlayer.PlayLooping();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void muteButton_Click(object sender, EventArgs e)
{
if (muteButton.Text == "Mute")
{
muteButton.Text = "Unmute";
_soundPlayer.Stop();
}
else
{
muteButton.Text = "Mute";
_soundPlayer.PlayLooping();
}
}
private void playButton_Click(object sender, EventArgs e)
{
ans1.Visible = true;
ans2.Visible = true;
ans3.Visible = true;
ans4.Visible = true;
playButton.Visible = false;
}
public void question()
{
if (questionNr == 1)
{
questionLabel.Text = "What is Chuck's full name?";
ans1.Text = "Charles Irving Bartowski";
ans2.Text = "Charles Richard Bartowski";
ans3.Text = "Charles Luke Bartowski";
ans4.Text = "Zachary Strahovski";
}
}
private void ans1_Click(object sender, EventArgs e)
{
}
private void ans2_Click(object sender, EventArgs e)
{
}
private void ans3_Click(object sender, EventArgs e)
{
}
private void ans4_Click(object sender, EventArgs e)
{
}
}
}
Form where you invoke the question() method. First call that method from where you need.
eg: FormLoad/Button click etc..Then try
public Form1()
{
InitializeComponent();
_soundPlayer = new SoundPlayer("song.wav");
question();
}
It's good if you put a break point in your Form Load event and see how your code executed.Then you'll get an idea about the flow of your code.

Categories