Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace Threding
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Paralel code execution
- // https://www.youtube.com/watch?v=Fzckqczmgd0
- // synhronous/single threated execution
- //Function1();
- //Function2();
- // 1. Foreground threads
- // Paralel/multithreated asynchronous execution
- // forground threads
- // Thread obj1 = new Thread(Function1);
- // Thread obj2 = new Thread(Function2);
- // start the paralel threads
- // forground threads - even if the main finishes the threads will continue
- // obj1.Start();
- // obj2.Start();
- // here the main app quits but the foreground threads continue
- // Background threads will quit if the main app quits
- // 2. Background thread
- // By default the thread is forground
- Thread obj1 = new Thread(Function1);
- // !!! To make it background
- obj1.IsBackground = true; // make it beackground
- obj1.Start();
- Console.WriteLine("The main application has exited");
- }
- // For forground thread
- //static void Function1()
- //{
- // for (int i = 0; i < 10; i++)
- // {
- // Console.WriteLine("Function 1 executed " + i.ToString());
- // // to see the thread execution clearly we wait for 4 s
- // Thread.Sleep(4000);
- // }
- //}
- // For background thread
- static void Function1()
- {
- Console.WriteLine("Function 1 is entered ...");
- Console.ReadLine(); // wait here
- Console.WriteLine("Function 1 is exited ...");
- }
- static void Function2()
- {
- for (int i = 0; i < 10; i++)
- {
- Console.WriteLine("Function 2 executed " + i.ToString());
- // to see the thread execution clearly we wait for 4 s
- Thread.Sleep(4000);
- }
- }
- }
- }
- /*
- Function 1 executed 0
- Function 1 executed 1
- Function 1 executed 2
- Function 1 executed 3
- Function 1 executed 4
- Function 1 executed 5
- Function 1 executed 6
- Function 1 executed 7
- Function 1 executed 8
- Function 1 executed 9
- Function 2 executed 0
- Function 2 executed 1
- Function 2 executed 2
- Function 2 executed 3
- Function 2 executed 4
- Function 2 executed 5
- Function 2 executed 6
- Function 2 executed 7
- Function 2 executed 8
- Function 2 executed 9
- Paralel execution
- Function 2 executed 0
- Function 1 executed 0
- Function 1 executed 1
- Function 2 executed 1
- Function 2 executed 2
- Function 1 executed 2
- Function 2 executed 3
- Function 1 executed 3
- Function 2 executed 4
- Function 1 executed 4
- Function 2 executed 5
- Function 1 executed 5
- Function 2 executed 6
- Function 1 executed 6
- Function 2 executed 7
- Function 1 executed 7
- Function 2 executed 8
- Function 1 executed 8
- Function 1 executed 9
- Function 2 executed 9
- Function 1 is entered ...
- The main application has exited
- eww
- Function 1 is exited ...
- background thread
- The main application has exited
- Function 1 is entered ...
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement