The idea here is to show a little bit about parallel programming and the way I understand it – as far as I am mainly a VBA developer, I do not understand it, because Microsoft did not think that it can be useful in VBA. 🙂
Anyhow, the idea of the parallel programming (or multiple thread programming) is that there can be tasks carried out in the same time, and not like in VBA (or PHP and the other scripting languages) just one task. It is really useful, if you know how to use it. Its like having multiple tasks in a program, which do not wait for each other, but carry out simultaneously. Pretty much that is it.
In C#, there is a .NET built-in library, which you can use to do it – System.Threading
. In the current example I create 3 Threads and I give to two of them a repetitive task to write on the console some string. Then I make the Thread sleep a bit and then I abort the threads. The result is seen on the screenshot.
Here comes the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System.Threading; namespace threads { class ThreadsExample { static void Main() { Writer oWriter1 = new Writer(); Writer oWriter2 = new Writer(); Writer oWriter3 = new Writer(); Thread oThread1 = new Thread(() => oWriter1.WriteSomething("I am the first")); Thread oThread2 = new Thread(() => oWriter2.WriteSomething("2222")); Thread oThread3 = new Thread(() => oWriter3.WriteSomethingOnce()); oThread1.Start(); oThread2.Start(); oThread3.Start(); Thread.Sleep(100); oThread1.Abort(); oThread2.Abort(); oThread3.Abort(); } } } |
And the Writer class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; namespace threads { public class Writer { public void WriteSomething(string strSomething) { while (true) { Console.WriteLine(strSomething); } } public void WriteSomethingOnce() { Console.WriteLine("Writing just once"); } } } |
Yup that’s all.
The code is in GitHub as well.