Csharp/CSharp Tutorial/Thread/Current Thread — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 15:20, 26 мая 2010

Context Manipulator

<source lang="csharp">using System; using System.Runtime.Remoting.Contexts; using System.Threading;

 public class MyClass
 {
   public MyClass()
   {
     Context ctx = Thread.CurrentContext;
     Console.WriteLine("{0} object in context {1}", this.ToString(), ctx.ContextID);
     foreach(IContextProperty itfCtxProp in ctx.ContextProperties)
       Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name);
   }
 }
 public class MyClassTS : ContextBoundObject
 {
   public MyClassTS()
   {
     Context ctx = Thread.CurrentContext;
           Console.WriteLine("{0} object in context {1}",this.ToString(), ctx.ContextID);
           foreach (IContextProperty itfCtxProp in ctx.ContextProperties)
               Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name);
   }
 }
 class Program
 {
   static void Main(string[] args)
   {
           MyClass sport = new MyClass();
           MyClass sport2 = new MyClass();
           MyClassTS synchroSport = new MyClassTS();
       }
 }</source>

Current Thread HashCode

<source lang="csharp">using System; using System.Threading; public class MainClass {

   private static void ThreadFunc() {
       Console.WriteLine( "Thread.CurrentThread.GetHashCode() {0}!",Thread.CurrentThread.GetHashCode() );
   }
   
   static void Main() {
       Thread newThread = new Thread( new ThreadStart(ThreadFunc) );
       Console.WriteLine( "Main Thread is {0}", Thread.CurrentThread.GetHashCode() );
       
       newThread.Start();
       newThread.Join();
       
       Thread.Sleep(2000);
   }

}</source>

Main Thread is 1
Thread.CurrentThread.GetHashCode() 3!

CurrentThread: Name, ApartmentState, IsAlive, Priority, ThreadState

<source lang="csharp">using System; using System.Threading; class MainClass {

 // [MTAThread]
 [STAThread]
 static void Main(string[] args)
 {
   Thread primaryThread = Thread.CurrentThread;
   primaryThread.Name = "ThePrimaryThread";
   Console.WriteLine("Thread Name: {0}", primaryThread.Name);
   Console.WriteLine("Alive: {0}", primaryThread.IsAlive);
   Console.WriteLine("Priority Level: {0}", primaryThread.Priority);      
   Console.WriteLine("Thread State: {0}", primaryThread.ThreadState);
 }

}</source>

Thread Name: ThePrimaryThread
Alive: True
Priority Level: Normal
Thread State: Running