using System;
using System.Windows.Forms;
using System.Threading;
namespace UI_Threading_Example
{
//declare the delegate that we'll use to launch our worker function in a separate thread
public delegate void workerFunctionDelegate(int totalSeconds);
//declare the delegate that we'll use to call the function that displays text in our text box
public delegate void poplateTextBoxDelegate(string text);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//this function will simply write text to our text box
//this function will later be called from a worker thread through the use of a delegate using the Invoke method on the form
void populateTextBox(string text)
{
textBox1.Text = textBox1.Text + " " + text;
}
//this function simulates "work" by simply counting from 1 to totalSeconds
void workerFunction(int totalSeconds)
{
for (int count = 1; count <= totalSeconds ; count++)
{
//we use this.Invoke to send information back to our UI thread with a delegate
//if we were to try to access the text box on the UI thread directly from a different thread, there would be problems
this.Invoke(new poplateTextBoxDelegate(populateTextBox), new object[] { count.ToString() });
Thread.Sleep(1000);
}
}
//this function is executed when we click the first button in the windows form
//this is the PROPER WAY to do work in a UI situation
//the worker function is launched in a separate thread so that our UI will remain responsive while it does work
private void buttonNewThread_Click(object sender, EventArgs e)
{
workerFunctionDelegate w = workerFunction;
w.BeginInvoke(15, null, null);
}
//this function is executed when we click the second button in the windows form
//it's an example of WHAT NOT TO DO because if we click this button
//the UI will become completely unresponsive for 15 seconds while the worker fucntion is executed
private void buttonCurrentThread_Click(object sender, EventArgs e)
{
workerFunction(15);
}
}