C# Threading

Created by
Wednesday, April 27, 2016

In Computer Science a “thread” is simply the component of a process. Programs can be single-threaded or multi-threaded programs.There are plenty of resources online that will explain in finer detail the threading concept so for the purpose of this article i will provide some simple code that you could execute on a console application to further display a thread in progress.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace threadingExample
{
    class Program
    {
        static void Main()
        {
            // Start a thread running the WriteY method.
            Thread t = new Thread(Write2);
            t.Start();
 
            // At the same time run on the main thread.
            for (int i = 0; i < 1000; i++) Console.WriteLine("1");
 
            Console.ReadLine();
        }
 
        static void Write2()
        {
            for (int i = 0; i < 1000; i++) Console.WriteLine("2");
        }
    }
}

 

Above we have a simple console application that starts a single threaded application. We instantiate a Thread Object and call that objects start method. The application begins with the main thread t printing our method for Write2. At the same time the main thread prints 1. On a multicore process machine the two threads can execute in parallel.  The result is of repeated segments of 1′s and 2′s. This is due to the way in which the console handles concurrent requests.

 

Below is a pretty simple use case for threading in a software situation.

thread

Tags:
c#
threading
0
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
0 comments