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;
}
}
}

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]