[C#] Multithreading

All tutorials created in C# to be posted in here.
3 posts Page 1 of 1
Contributors
User avatar
DreadNought
VIP - Donator
VIP - Donator
Posts: 116
Joined: Fri Jan 08, 2010 12:37 pm

[C#] Multithreading
DreadNought
##I have posted this in the wrong section, request move to the tut section

Hey,

So today I am going to write a very quick tut on multithreads! This will allow you to create multipile threads that can execute code all at the same time!

Okay so first we should add at the top of our class:
Code: Select all
using System.Threading;
This will allow us to access all the Threading methods and class's provided by the .net Framework!

So we have this so far(I am using a console application for this example:
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadingTut
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}
We are now going to create an Array of threads to hold all of our threads! Creating a thread class will allow you to have more customizable threading but an Array of threads works just fine for this.

To do that we are going to add this code inside the Main method(Where your application entry point is)
Code: Select all
Thread[] Threads = new Thread[2];
We can change the number inside the "[ ]" brackets to our number of threads, You should understand Arrays before attempting this(I will cover that via video another day)
So now our code looks like
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadingTut
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread[] Threads = new Thread[2];
        }
    }
}
So if you understand arrays you will know that even though it says "[2]" that actually means it will claim there are only "[1]" spaces in the Thread array but really there are two because you can assign 0 too. (Remember, array's are technically unsafe code, so they start at the value 0)

So now we are going to Initalize two threads by adding:
Code: Select all
Threads[0] = new Thread(new ThreadStart(TestOne));
Threads[1] = new Thread(new ThreadStart(TestTwo));
There in our array of threads, Value [0] and [1] have been assigned to a thread(before they were null as the Thread class hadn't been initialized and assigned)

Now "TestOne" and "TestTwo" are the methods('voids') that our threads will execute when they hae been started

So our code now looks like
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadingTut
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread[] Threads = new Thread[2];

            Threads[0] = new Thread(new ThreadStart(TestOne));
            Threads[1] = new Thread(new ThreadStart(TestTwo));
        }
        public static void TestOne()
        {
        }
        public static void TestTwo()
        {
        }
    }
}
Okay, so thats all good and well, but the threads wont execute those methods untill they have been started, so I foreach code should do the job just fine. Under where I initialize the threads I add:
Code: Select all
            foreach (Thread _thread in Threads)
                _thread.Start();
Which would mean the same as
Code: Select all
            foreach (Thread _thread in Threads)
            {
                _thread.Start();
            }
It makes no difference. So our code now looks like:
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadingTut
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread[] Threads = new Thread[2];

            Threads[0] = new Thread(new ThreadStart(TestOne));
            Threads[1] = new Thread(new ThreadStart(TestTwo));
            foreach (Thread _thread in Threads)
            {
                _thread.Start();
            }
        }
        public static void TestOne()
        {
        }
        public static void TestTwo()
        {
        }
    }
}
But our methods dont do anything because theres no code!
So lets add some code;

I am going to place two ints at the top of the Main methods:
Code: Select all
public static int b = 0;
public static int bb = 500;
Add a while loop and some code inside both of the Threads so our code looks like this:
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadingTut
{
    class Program
    {
        public static int b = 0;
        public static int bb = 500;
        static void Main(string[] args)
        {
            Thread[] Threads = new Thread[2];

            Threads[0] = new Thread(new ThreadStart(TestOne));
            Threads[1] = new Thread(new ThreadStart(TestTwo));
            foreach (Thread _thread in Threads)
            {
                _thread.Start();
            }
        }
        public static void TestOne()
        {
            while (true)
            {
                if (b < 100)
                {
                    b++;
                    Console.WriteLine("The value of the int 'b' is currently at: {0}", b);
                }
                Thread.Sleep(100);
            }
        }
        public static void TestTwo()
        {
            while (true)
            {
                if (bb < 600)
                {
                    bb++;
                    Console.WriteLine("The value of the int 'bb' is currently at: {0}", bb);
                }
                Thread.Sleep(100);
            }
        }
    }
}

Thread.Sleep(100); will mean that method will execute every 100ms, once the code in the while loops is finished in this case when b = 100 and bb = 600 our threads WONT stop as you cna add multipile actions inside a threads method execute, in order to stop the thread(s) once its execute you would need to make the Array static and make it public(which means put it under the ints like so:
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadingTut
{
    class Program
    {
        public static int b = 0;
        public static int bb = 500;
        public static Thread[] Threads = new Thread[2];
        static void Main(string[] args)
        {
            Threads[0] = new Thread(new ThreadStart(TestOne));
            Threads[1] = new Thread(new ThreadStart(TestTwo));
            foreach (Thread _thread in Threads)
            {
                _thread.Start();
            }
        }
        public static void TestOne()
        {
            while (true)
            {
                if (b < 100)
                {
                    b++;
                    Console.WriteLine("The value of the int 'b' is currently at: {0}", b);
                    if (b == 100)
                        Threads[0].Abort();
                }
                Thread.Sleep(100);
            }
        }
        public static void TestTwo()
        {
            while (true)
            {
                if (bb < 600)
                {
                    bb++;
                    Console.WriteLine("The value of the int 'bb' is currently at: {0}", bb);
                    if (bb == 100)
                        Threads[1].Abort();
                }
                Thread.Sleep(100);
            }
        }
    }
}
Our code should look like that, the while(true) command means while the thread is active it will always cycle, but since we Abort the thread the while(true) which as again means while the thread is active(which its now not as the thread has been aborted) will stop running so in return the thread stops running which means the code stops executing!

The result? Go code and find out yourself!

Please leave some feedback and a screenshot of your finished result in the Console application window of the result to show you really did do it!

Thankyou.

-Paralyzer
Bound and boom tech,
The Future Of Coding
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

Re: [C#] Multithreading
MrAksel
Its a good tutorial, but you might want to add some more pros and cons about threads. Like the problems about accessing controls from different threads than they were created on.
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
User avatar
DreadNought
VIP - Donator
VIP - Donator
Posts: 116
Joined: Fri Jan 08, 2010 12:37 pm

Re: [C#] Multithreading
DreadNought
That is simply avoided by either invoking the method/control or more simply Disabling cross threading; I'll add that into the tut lateron tonight.
Bound and boom tech,
The Future Of Coding
3 posts Page 1 of 1
Return to “C-Sharp Tutorials”