📜 ⬆️ ⬇️

Threads in C # .NET first steps

Dear readers, in this article I want to talk about such an important means of multitasking programming environment. NET, as multithreading. This article contains basic information, and is intended for the rapid development of the basics of multithreading in the C # language. However, I will not rant about the benefits of parallel execution of tasks, and move on to the sample code.

using System; using System.Threading; //      namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Thread myThread = new Thread(func); //    (Thread) myThread.Start(); //  for (int i = 0; i < 10; i++ ) { Console.WriteLine(" 1  " + i); Thread.Sleep(0); } Console.Read(); //   } //     static void func() { for (int i = 0; i < 10; i++) { Console.WriteLine(" 2  " + i.ToString()); Thread.Sleep(0); } 
What you should pay attention to in this program. Primarily this is the System.Threading namespace. This namespace contains classes that support multi-threaded programming. And it is there that contains the class Thread , which we use later in the code.
Next, we create a stream object.
 Thread myThread = new Thread(func); 

The constructor of this class must pass the name of the function returning void , which itself will be called in a parallel thread. Then we start our thread with the Start () method defined inside the newly created thread.

So, the main and minor streams in parallel execute an almost identical code, they count to 9 (as it was customized, from scratch), before that calling their own number. Pay attention to the static method Thread.Sleep (0) . It suspends the thread causing it for the number of milliseconds specified in the parameter. But in this case the parameter 0 is passed to it. This means that the thread must pause in order to allow the execution of another thread.

And in order for the console not to close ahead of time, we will expect keyboard input ( Console.Read ). As a result, your program will output the following to the console:
Stream 1 prints 0
Stream 2 prints 0
Stream 1 outputs 1
Stream 1 outputs 2
Stream 1 outputs 3
Stream 2 outputs 1
<...> etc.
')
Although the output will be different each time. It depends on many factors. It is worth taking into account that there are two types of flows: priority and background. Background threads automatically end when priority is completed. By default, the Main function in the priority stream is started and the remaining streams are created as background threads. That is why we must ensure that the main thread does not terminate before the end of the derivatives. In order to prevent this, we can use the IsAlive field, which returns true if the stream is active. Either the Join () method, which forces the thread in which it is called to wait for the completion of the thread to which it belongs.

However, we can change the types of flows ourselves. The IsBackground property of the stream determines whether the stream is background. Thus, we can make the thread a priority. myThread.IsBackground = false; However, we do not need to create a new thread inside the Main method. Let's create a class that will open a new thread in its own constructor. The class created by us will continue to deal with the account, but this time it will count to the specified number, due to the transfer of parameters to the stream.

 using System; using System.Threading; namespace ConsoleApplication1 { class Program { class myThread { Thread thread; public myThread(string name, int num) //          { thread = new Thread(this.func); thread.Name = name; thread.Start(num);//    } void func(object num)// ,   { for (int i = 0;i < (int)num;i++ ) { Console.WriteLine(Thread.CurrentThread.Name + "  " + i); Thread.Sleep(0); } Console.WriteLine(Thread.CurrentThread.Name + " "); } } static void Main(string[] args) { myThread t1 = new myThread("Thread 1", 6); myThread t2 = new myThread("Thread 2", 3); myThread t3 = new myThread("Thread 3", 2); Console.Read(); } } } 
Let us consider this example. The constructor of our myThread class takes 2 parameters: a string in which we define the name of the stream, and the number to which the count will be kept in the loop. In the constructor, we create a stream associated with the func function of this object. Next, we assign a name to our stream using the Name field of the created stream. And we start our thread by passing the Start function an argument.

Note that a function called by a thread can take only 1 argument, and only of type object. In the func function, the for loop counts to the number passed to it as an argument, and the thread ends. In the Main function, we create 3 test objects, whose operation will output approximately the following text to the console.

Thread 1 prints 0
Thread 1 prints 1
Thread 2 prints 0
Thread 2 prints 1
Thread 2 prints 2
Thread 2 has ended
<...>

With this example, I want to finish my article. And although many means of working with threads have remained unaffected by me, I dare to hope that the information presented by me will be useful.

Source: https://habr.com/ru/post/126495/


All Articles