
While developing desktop applications, we may sometimes be required to work with Multithreaded programming. This can also help optimize the software’s performance, as it makes the most of the CPU core(s) and thus provides better throughput/results. We also refer to this type of implementation as ‘multi-tasking’. In such a case, our application will be able to do different types of tasks at the same time, in parallel.
For Example, just consider a simple database-based desktop application development scenario, where your application will retrieve a series of data and show it to the user. Now, if the database connectivity is slow for some reason, your application will typically get stuck. Users won’t be able to do anything else but wait for the process to be finished. In such cases, we can nicely design a thread-based implementation, which will allow users to do other actions while your application is retrieving data from a database and improves usability on a large scale.
A simple classic thread Example:
Let’s start with a very simple single-threaded example. The following code examples will show a simple thread-running strategy. The thread will run 50 times with an interval of 500 milliseconds between each run.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
ThreadStart testThreadStart = new ThreadStart(new Program().testThread);
Thread testThread = new Thread(testThreadStart);
testThread.Start();
Console.ReadLine();
}
public void testThread()
{
//executing in thread
int count = 0;
while (count++ < 50)
{
Console.WriteLine("Thread Executed "+count+" times");
Thread.Sleep(500);
}
}
}
}
Code language: JavaScript (javascript)
As you can see, first, we need to define a ‘ThreadStart’ instance with the function that will be executed in a thread. Then, this instance is required as a parameter in our ‘Thread’ class initialization. After calling the ‘start’ method, the function will be called for execution in parallel to other processes.
Also, remember that the function will be called only once. Keeping it alive is our responsibility. That means we will need to run it inside a for loop until it meets a certain criteria. The ‘Sleep’ method waits for that particular thread for the given amount of time(in milliseconds) before executing the next statement.
Multithreaded Programming With Classic Threads:
Let’s move one step ahead to see how more than one thread can be run in parallel. The following code snippet will demonstrate such a scenario. Though I am using two threads only here, you can add as many as you want.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
ThreadStart testThread1Start = new ThreadStart(new Program().testThread1);
ThreadStart testThread2Start = new ThreadStart(new Program().testThread2);
Thread[] testThread = new Thread[2];
testThread[0] = new Thread(testThread1Start);
testThread[1] = new Thread(testThread2Start);
foreach (Thread myThread in testThread)
{
myThread.Start();
}
Console.ReadLine();
}
public void testThread1()
{
//executing in thread
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 1 Executed "+count+" times");
Thread.Sleep(1);
}
}
public void testThread2()
{
//executing in thread
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 2 Executed " + count + " times");
Thread.Sleep(1);
}
}
}
}
Code language: JavaScript (javascript)
After running the application, you should see an output something like below:
Note that the output won’t always be exact; it completely depends on how the OS provides schedules to the CPU for thread execution.
Working With ThreadPool:
So, as we have seen so far in the above code examples, it uses ‘Thread’ in raw mode. However, we can simplify the thread running process with the use of the ‘ThreadPool’ class that is provided by the .NET framework and is very helpful for quick implementation of multithreaded programming. All we have to do is queue the function we want running in the thread. And it will automatically start executing them. The following code will demonstrate this simplified usage of ‘ThreadPool’ .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new Program().testThread1);
ThreadPool.QueueUserWorkItem(new Program().testThread2);
Console.ReadLine();
}
public void testThread1(Object threadContext)
{
//executing in thread
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 1 Executed "+count+" times");
Thread.Sleep(100);
}
}
public void testThread2(Object threadContext)
{
//executing in thread
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 2 Executed " + count + " times");
Thread.Sleep(100);
}
}
}
}
Code language: JavaScript (javascript)
Further References:
You will want to look into the MSDN tutorial on the thread and MSDN documentation on the thread pool for an in-depth overview of the classes. Happy coding 🙂
Discover more from CODESAMPLEZ.COM
Subscribe to get the latest posts sent to your email.
these programs dealwith consol application but what about form applicationsis there any way to do parallel programming in form applications.?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
namespace APP6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Mensagem m = new Mensagem();
Thread[] t = new Thread[6];
for (int i = 0; i < 6; i++)
{
t[i] = new Thread(new ThreadStart(m.p));
t[i].Name = "Thread-" + i.ToString();
t[i].Start();
}
}
}
class Mensagem
{
public void p()
{
Thread.Sleep(100);
MessageBox.Show("Rodando a " + Thread.CurrentThread.Name);
}
}
}
Hi How I’m interested in executing an application command on multiple servers in parallel using multi-threading if possible. For example, stop app, start app, checkversion, etc. on 10 servers to perform routine system patching. Let’s say 3 for testing. We can try pinging them in parallel first. I’m using MS Visual Studio 2017 c# WPF form. Do you have any tips with this approach using mult-threading please?