當前位置: 首頁>>代碼示例>>C#>>正文


C# Thread類代碼示例

本文整理匯總了C#中System.Threading.Thread的典型用法代碼示例。如果您正苦於以下問題:C# Thread類的具體用法?C# Thread怎麽用?C# Thread使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Thread類屬於System.Threading命名空間,在下文中一共展示了Thread類的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: ThreadProc

//引入命名空間
using System;
using System.Threading;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample {
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends.
    public static void ThreadProc() {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", i);
            // Yield the rest of the time slice.
            Thread.Sleep(0);
        }
    }

    public static void Main() {
        Console.WriteLine("Main thread: Start a second thread.");
        // The constructor for the Thread class requires a ThreadStart 
        // delegate that represents the method to be executed on the 
        // thread.  C# simplifies the creation of this delegate.
        Thread t = new Thread(new ThreadStart(ThreadProc));

        // Start ThreadProc.  Note that on a uniprocessor, the new 
        // thread does not get any processor time until the main thread 
        // is preempted or yields.  Uncomment the Thread.Sleep that 
        // follows t.Start() to see the difference.
        t.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++) {
            Console.WriteLine("Main thread: Do some work.");
            Thread.Sleep(0);
        }

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
        t.Join();
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
        Console.ReadLine();
    }
}
開發者ID:.NET開發者,項目名稱:System.Threading,代碼行數:43,代碼來源:Thread

示例2: Main

//引入命名空間
using System;
using System.Diagnostics;
using System.Threading;

public class Example
{
   public static void Main()
   {
      var th = new Thread(ExecuteInForeground);
      th.Start();
      Thread.Sleep(1000);
      Console.WriteLine("Main thread ({0}) exiting...", 
                        Thread.CurrentThread.ManagedThreadId); 
   }
   
   private static void ExecuteInForeground()
   {
      DateTime start = DateTime.Now;
      var sw = Stopwatch.StartNew();
      Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority);
      do { 
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000.0);
         Thread.Sleep(500);
      } while (sw.ElapsedMilliseconds <= 5000);
      sw.Stop(); 
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading,代碼行數:33,代碼來源:Thread

輸出:

Thread 3: Running, Priority Normal
Thread 3: Elapsed 0.00 seconds
Thread 3: Elapsed 0.51 seconds
Main thread (1) exiting...
Thread 3: Elapsed 1.02 seconds
Thread 3: Elapsed 1.53 seconds
Thread 3: Elapsed 2.05 seconds
Thread 3: Elapsed 2.55 seconds
Thread 3: Elapsed 3.07 seconds
Thread 3: Elapsed 3.57 seconds
Thread 3: Elapsed 4.07 seconds
Thread 3: Elapsed 4.58 seconds

示例3: Main

//引入命名空間
using System;
using System.Diagnostics;
using System.Threading;

public class Example
{
   public static void Main()
   {
      var th = new Thread(ExecuteInForeground);
      th.Start(4500);
      Thread.Sleep(1000);
      Console.WriteLine("Main thread ({0}) exiting...", 
                        Thread.CurrentThread.ManagedThreadId); 
   }
   
   private static void ExecuteInForeground(Object obj)
   {
      int interval;
      try {
         interval = (int) obj;
      }
      catch (InvalidCastException) {
         interval = 5000;
      }
      DateTime start = DateTime.Now;
      var sw = Stopwatch.StartNew();
      Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority);
      do { 
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000.0);
         Thread.Sleep(500);
      } while (sw.ElapsedMilliseconds <= interval);
      sw.Stop(); 
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading,代碼行數:40,代碼來源:Thread

輸出:

Thread 3: Running, Priority Normal
Thread 3: Elapsed 0.00 seconds
Thread 3: Elapsed 0.52 seconds
Main thread (1) exiting...
Thread 3: Elapsed 1.03 seconds
Thread 3: Elapsed 1.55 seconds
Thread 3: Elapsed 2.06 seconds
Thread 3: Elapsed 2.58 seconds
Thread 3: Elapsed 3.09 seconds
Thread 3: Elapsed 3.61 seconds
Thread 3: Elapsed 4.12 seconds

示例4: Object

//引入命名空間
using System;
using System.Threading;

public class Example
{
   static Object obj = new Object();
   
   public static void Main()
   {
      ThreadPool.QueueUserWorkItem(ShowThreadInformation);
      var th1 = new Thread(ShowThreadInformation);
      th1.Start();
      var th2 = new Thread(ShowThreadInformation);
      th2.IsBackground = true;
      th2.Start();
      Thread.Sleep(500);
      ShowThreadInformation(null); 
   }
   
   private static void ShowThreadInformation(Object state)
   {
      lock (obj) {
         var th  = Thread.CurrentThread;
         Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId);
         Console.WriteLine("   Background thread: {0}", th.IsBackground);
         Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread);
         Console.WriteLine("   Priority: {0}", th.Priority);
         Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name);
         Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name);
         Console.WriteLine();
      }   
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading,代碼行數:34,代碼來源:Thread

輸出:

Managed thread #6:
Background thread: True
Thread pool thread: False
Priority: Normal
Culture: en-US
UI culture: en-US

Managed thread #3:
Background thread: True
Thread pool thread: True
Priority: Normal
Culture: en-US
UI culture: en-US

Managed thread #4:
Background thread: False
Thread pool thread: False
Priority: Normal
Culture: en-US
UI culture: en-US

Managed thread #1:
Background thread: False
Thread pool thread: False
Priority: Normal
Culture: en-US
UI culture: en-US

示例5: Main

//引入命名空間
using System;
using System.Diagnostics;
using System.Threading;

public class Example
{
   public static void Main()
   {
      var th = new Thread(ExecuteInForeground);
      th.IsBackground = true;
      th.Start();
      Thread.Sleep(1000);
      Console.WriteLine("Main thread ({0}) exiting...", 
                        Thread.CurrentThread.ManagedThreadId); 
   }
   
   private static void ExecuteInForeground()
   {
      DateTime start = DateTime.Now;
      var sw = Stopwatch.StartNew();
      Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority);
      do { 
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000.0);
         Thread.Sleep(500);
      } while (sw.ElapsedMilliseconds <= 5000);
      sw.Stop(); 
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading,代碼行數:34,代碼來源:Thread

輸出:

Thread 3: Background, Priority Normal
Thread 3: Elapsed 0.00 seconds
Thread 3: Elapsed 0.51 seconds
Main thread (1) exiting...

示例6: new Thread()

//引入命名空間
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;

public class MainClass
{
    public static void Main()
    {
        Thread paramThread = new Thread(ParameterizedWorkerOperation);
        paramThread.Start("Test");

        paramThread.Join();
    }
    private static void ParameterizedWorkerOperation(object o)
    {
        Console.WriteLine("Param worker: {0}", o);
    }
}
開發者ID:C#程序員,項目名稱:System.Threading,代碼行數:26,代碼來源:Thread


注:本文中的System.Threading.Thread類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。