CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming How To Work With Multithreaded Programming In C#.NET Application

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

Rana Ahsan February 18, 2013 3 Comments


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

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 🙂

Related

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

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Generate HTTP Requests using c#
  • Utilizing Config File In C#.NET Application
  • How To Work With Codeigniter Caching In PHP
  • Using Supervisord Web Interface And Plugin
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • LinQ To SQL Database Update Operations In C#

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in