Paul Maddox

Software development team leader specialising in Microsoft Visual C# and C++ from the Northwest of England. Experience working in a globalised business and team; understanding of enterprise business operation and practices; experience reporting to executive management Skills in numerous languages and technologies; knowledge of formal software development lifecycle; experience of architecture design

Monday, May 28, 2007

Creating a thread in C# - no nonsense code

There seem to be a lot of the more complicated C# threading tutorials out there, but I was more interested in the bare minimum that I can then build on the way I like. Here is a code sample to start a thread with a button on a form that will display a Hello message box every minute until the button is clicked again. To use the code, copy the functions to your class and adapt as needed.

using System.Threading;

public partial class Form1 : Form
{
Thread m_thread = null;

// Static method that we call threaded
public static void ThreadFunc()
{
while (true)
{
System.Windows.Forms.MessageBox.Show("Hello");
Thread.Sleep(60 * 1000); // wait 1 minute
}
}

// Event when we click our button
private void butStart_Click(object sender, EventArgs e)
{
if (m_thread == null)
{
m_thread = new Thread(new ThreadStart(ThreadFunc));
m_thread.Start();
}
else
{
m_thread.Abort();
m_thread = null;
}
}
}

0 Comments:

Post a Comment

<< Home