C# Multithreading Example Tutorial

For better performance we can use multithreading in our programm. We use thread for heavy processes like load data from database or during use of Internet, otherwise you will feel hanged your User Interface.

In c sharp it is very easy to use multithreading.

Note:- Don’t update controls like label or buttons with in thread, because your user interface is not part of new created thread. Every application have a main thread also called UI Thread that handle user interface. If you will try to call user controls in background thread (new thread) then you will face an Exception of different thread.

Following example is showing how to use background thread (multi threading) in c#

// This thread will call a function Login
System.Threading.Thread thread = new System.Threading.Thread(Login);
thread.Start();
private void Login()
{
// network communication, or any process
}

Complete example with handling of user inteface is given below:

[sociallocker]

public partial class fmLogin : Form
{
	private EventHandler onLoginThreadComplete;
	
	 private void fmLogin_Load(object sender, EventArgs e)
	{
		onLoginThreadComplete = new EventHandler(onLoginThreadCompleteFunction);
	}

	private void btnLogin_Click(object sender, EventArgs e)
	{
		// Disable all controls to save frequently click by end user.
		// EnableControls(false);
		
		// Background thread, that will call a function Login
		System.Threading.Thread thread = new System.Threading.Thread(Login);
		thread.Start();
	}

	private void Login()
	{
		// Validating user input
		// We can call MessageBox in background thread
		if (String.IsNullOrEmpty(tbEmail.Text.Trim()))
		{
			MessageBox.Show("Please enter Email.", "Image Box", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
		}
		else if (String.IsNullOrEmpty(tbPassword.Text.Trim()))
		{
			MessageBox.Show("Please enter Password.", "Image Box", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
		}
		else
		{
			// network communication, or any process
			
			// Call UI Thread to open new form 
			 BeginInvoke(onLoginThreadComplete, new object[] { this, EventArgs.Empty });
		}
				
	}

	private void onLoginThreadCompleteFunction(object sender, EventArgs e)
	{
		FmDashBoard form = new FmDashBoard();
		form.Show();
	}
		
}

[/sociallocker]

Leave a comment

Your email address will not be published. Required fields are marked *