• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / How To Work With Multithreaded Programming In C#.NET Application

How To Work With Multithreaded Programming In C#.NET Application

February 18, 2013 by Rana Ahsan 3 Comments

multithreaded programming

While working with desktop application development, we may sometimes required to work with Multithreaded programming. It can also help in optimizing the performance of the software as it make most usage of the CPU core(s) and thus providing better throughput/results. We refer to this type of implementation as ‘multi-tasking’ also. As in such case, our application will be able to do different type 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 to user. Now, if the database connectivity is slow for some reason, your application will normally get stuck. User 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 user to do other actions while your application is retrieving data from a database, and improves the usability in a large-scale.

A simple classic thread Example:

Lets start with a very simple single thread 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 running.

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

As you can see, first we need to define a ‘ThreadStart’ instance with the function that we will need to be executed in thread. Then, this instance are required as 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. to keep it alive is our own responsibility. That means, we will need to run it inside a for loop until it satisfy a certain criteria. The ‘Sleep’ method waits that particular thread for the given amount of time(in milliseconds) before executing next statement.

Multithreaded Programming With Classic Threads:

Lets move one step ahead to see how more than one threads can be run in parallel. Following code snippet will demonstrate such scenario. Though, I am using two threads only here, you can add as many you want to it as per your need.

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

After running the application, you should see an output something like below:
Multithreaded programming Example Output

Note that, the output won’t be exact always, it completely depends on how OS provides schedules to CPU for execution of the thread.

Working With ThreadPool:

So, as we have seen so far in above code examples, uses ‘Thread’ in raw mode. However, we can simplify the thread running process with use of ‘ThreadPool’ class that is provided by .NET framework and is very much helpful for quick implementation of multithreaded programming. All we have to do is to queue the function we want running in 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);
            }
        }
    }
}

Further References:

You will may want to look into msdn tutorial on thread and msdn documentation on thread-pool for in-depth overview of the classes. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: .net, c#, thread

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. ravi says

    January 22, 2015 at 5:14 am

    these programs dealwith consol application but what about form applicationsis there any way to do parallel programming in form applications.?

    Reply
  2. Francisco Araújo says

    May 16, 2016 at 1:44 am

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

    }

    Reply
  3. Jay says

    September 27, 2017 at 11:25 pm

    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?

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023