Thread problem

  • Thread starter Thread starter TintinMalin
  • Start date Start date
T

TintinMalin

Guest
Hey Fellas,


I encountered a problem that I have used successfully in past hundreds of time.

I started a thread which update a textbox on the form based on a value.

That value is being updated by the main class.

For some reason as soon as the loop to update the value goes in, the thread disappears and no longer updates the text box.

ANy input is much appreciated

Here's the code, the function initiating the thread is Button1_Click

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

public class InvokeThreadSafeForm : Form
{
private delegate void SafeCallDelegate();
private Button button1;
private TextBox textBox1;
private Thread thread2 = null;
private int Diff = 0;
[STAThread]
static void Main()
{
Application.SetCompatibleTextRenderingDefault(false);
Application.EnableVisualStyles();
Application.Run(new InvokeThreadSafeForm());
}
public InvokeThreadSafeForm()
{
button1 = new Button
{
Location = new Point(15, 55),
Size = new Size(240, 20),
Text = "Set text safely"
};
button1.Click += new EventHandler(Button1_Click);
textBox1 = new TextBox
{
Location = new Point(15, 15),
Size = new Size(240, 20)
};
Controls.Add(button1);
Controls.Add(textBox1);
}

private void Button1_Click(object sender, EventArgs e)
{
thread2 = new Thread(new ThreadStart(SetText));
thread2.Start();
while( true )
{

Thread.Sleep(1000);
Diff++;
}

}

private void WriteTextSafe()
{
if (textBox1.InvokeRequired)
{
var d = new SafeCallDelegate(WriteTextSafe);
textBox1.Invoke(d);
}
else
{
textBox1.Text = Diff.ToString();
}
}

private void SetText()
{
while (true)
{
WriteTextSafe();
}
}
}

Continue reading...
 
Back
Top