radidim

microsoftThreading.cs

Aug 23rd, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. // Simple threading scenario:  Start a static method running
  5. // on a second thread.
  6. public class ThreadExample {
  7.     // The ThreadProc method is called when the thread starts.
  8.     // It loops ten times, writing to the console and yielding
  9.     // the rest of its time slice each time, and then ends.
  10.     public static void ThreadProc() {
  11.         for (int i = 0; i < 10; i++) {
  12.             Console.WriteLine("ThreadProc: {0}", i);
  13.             // Yield the rest of the time slice.
  14.             Thread.Sleep(0);
  15.         }
  16.     }
  17.  
  18.     public static void Main() {
  19.         Console.WriteLine("Main thread: Start a second thread.");
  20.         // The constructor for the Thread class requires a ThreadStart
  21.         // delegate that represents the method to be executed on the
  22.         // thread.  C# simplifies the creation of this delegate.
  23.         Thread t = new Thread(new ThreadStart(ThreadProc));
  24.  
  25.         // Start ThreadProc.  Note that on a uniprocessor, the new
  26.         // thread does not get any processor time until the main thread
  27.         // is preempted or yields.  Uncomment the Thread.Sleep that
  28.         // follows t.Start() to see the difference.
  29.         t.Start();
  30.         //Thread.Sleep(0);
  31.  
  32.         for (int i = 0; i < 4; i++) {
  33.             Console.WriteLine("Main thread: Do some work.");
  34.             Thread.Sleep(0);
  35.         }
  36.  
  37.         Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
  38.         t.Join();
  39.         Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
  40.         Console.ReadLine();
  41.     }
  42. }
Add Comment
Please, Sign In to add comment