Csharp/C Sharp by API/System.Threading/Thread

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

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.rupilerServices;
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);
    }
}


Thread.Abort()

  
using System;
using System.Threading;
class MainClass
{
  static int MyCount = 0;
  static void Main(string[] args)
  {
    MyClassThread me = new MyClassThread();
    Thread MyNewThread = new Thread(new ThreadStart(me.MyThread));
    MyNewThread.Start();
    if (MyCount == 0)
      MyNewThread.Abort();
  }
}
class MyClassThread
{
  public void MyThread()
  {
  }
}


Thread.AllocateDataSlot

  
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.rupilerServices;
using System.Security;
using System.Text;
using System.Threading;
public class MainClass
{
    public static void Main()
    {
        LocalDataStoreSlot slot = Thread.AllocateDataSlot();
        Thread.SetData(slot, 63);
        int slotValue1 = (int)Thread.GetData(slot);
        Console.WriteLine(slotValue1);
    }
}


Thread.AllocateNamedDataSlot

  
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.rupilerServices;
using System.Security;
using System.Text;
using System.Threading;

public class MainClass
{
    public static void Main()
    {
        Thread.SetData(Thread.AllocateNamedDataSlot("TestSlot"), 126);
        int slotValue2 = (int)Thread.GetData(Thread.GetNamedDataSlot("TestSlot"));
        Console.WriteLine(slotValue2);
    }
}


Thread.CurrentContext

  
  
using System;
using System.Threading;
class Program {
    static void Main(string[] args) {
        Thread primaryThread = Thread.CurrentThread;
        primaryThread.Name = "ThePrimaryThread";
        Console.WriteLine("Name of current AppDomain: {0}", Thread.GetDomain().FriendlyName);
        Console.WriteLine("ID of current Context: {0}", Thread.CurrentContext.ContextID);
        Console.WriteLine("Thread Name: {0}", primaryThread.Name);
        Console.WriteLine("Has thread started?: {0}", primaryThread.IsAlive);
        Console.WriteLine("Priority Level: {0}", primaryThread.Priority);
        Console.WriteLine("Thread State: {0}", primaryThread.ThreadState);
    }
}


Thread.CurrentCulture

  
using System;
using System.Globalization;
using System.Threading;
class MainClass
{
  public static void Main() 
  {
    Console.WriteLine(Thread.CurrentThread.CurrentCulture.Name);

  }
}


Thread.CurrentThread

  

using System;
using System.Globalization;
using System.Threading;
class MainClass
{
  public static void Main() 
  {
    Thread.CurrentThread.CurrentCulture=new CultureInfo("de-DE");

  }
}


Thread.GetData

  
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.rupilerServices;
using System.Security;
using System.Threading;
using System.Text;
public class MainClass
{
    public static void Main()
    {
        LocalDataStoreSlot slot = Thread.AllocateDataSlot();
        Thread.SetData(slot, 63);
        int slotValue1 = (int)Thread.GetData(slot);
        Console.WriteLine(slotValue1);
    }
}


Thread.GetHashCode()

  


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
class AddParams {
    public int a;
    public int b;
    public AddParams(int numb1, int numb2) {
        a = numb1;
        b = numb2;
    }
}
class Program {
    public static void Add(object data) {
        if (data is AddParams) {
            Console.WriteLine("ID of thread in Add(): {0}",Thread.CurrentThread.GetHashCode());
            AddParams ap = (AddParams)data;
            Console.WriteLine("{0} + {1} is {2}", ap.a, ap.b, ap.a + ap.b);
        }
    }
    static void Main(string[] args) {
        Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.GetHashCode());
        AddParams ap = new AddParams(10, 10);
        Thread t = new Thread(new ParameterizedThreadStart(Add));
        t.Start(ap);
        Console.ReadLine();
    }
}


Thread.Interrupt()

  
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
public class Form1 : System.Windows.Forms.Form {
    private System.Windows.Forms.ProgressBar progressBar1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private Thread fThread = null;
    private System.ruponentModel.Container components = null;
    public Form1() {
        this.progressBar1 = new System.Windows.Forms.ProgressBar();
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        this.progressBar1.Location = new System.Drawing.Point(24, 32);
        this.progressBar1.Name = "progressBar1";
        this.progressBar1.Size = new System.Drawing.Size(264, 23);
        this.progressBar1.TabIndex = 0;
        this.button1.Location = new System.Drawing.Point(24, 80);
        this.button1.Size = new System.Drawing.Size(136, 40);
        this.button1.Text = "Start Thread";
        this.button1.Click += new
             System.EventHandler(this.button1_Click);
        this.button2.Location = new System.Drawing.Point(168, 80);
        this.button2.Size = new System.Drawing.Size(120, 40);
        this.button2.Text = "Stop Thread";
        this.button2.Click += new
             System.EventHandler(this.button2_Click);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(704, 429);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
          this.button2,
          this.button1,
          this.progressBar1});
        this.ResumeLayout(false);
    }
    protected override void Dispose(bool disposing) {
        if (fThread != null) {
            fThread.Interrupt();
            fThread = null;
        }
    }
    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }
    private void UpdateProgress() {
        if (progressBar1.Value == progressBar1.Maximum) {
            progressBar1.Value = progressBar1.Minimum;
        }
        progressBar1.PerformStep();
    }

    public void ThreadProc() {
        try {
            MethodInvoker mi = new MethodInvoker(this.UpdateProgress);
            while (true) {
                this.BeginInvoke(mi);
                Thread.Sleep(500);
            }
        } catch (ThreadInterruptedException e) {
            Console.WriteLine(
              "Interruption Exception in Thread: {0}",
                  e);
        } catch (Exception we) {
            Console.WriteLine("Exception in Thread: {0}", we);
        }
    }
    private void button1_Click(object sender, System.EventArgs e) {
        fThread = new Thread(new ThreadStart(ThreadProc));
        fThread.IsBackground = true;
        fThread.Start();
    }
    private void button2_Click(object sender, System.EventArgs e) {
        fThread.Interrupt();
        fThread = null;
    }
}


Thread.IsAlive

  
using System;
using System.Threading;
public class ThreadState {
    static void WorkerFunction() {
        for (int i = 1; i < 50000; i++) {
            Console.WriteLine("Worker: " + Thread.CurrentThread.ThreadState);
        }
    }

    static void Main() {
        string ThreadState;
        Thread t = new Thread(new ThreadStart(WorkerFunction));
        t.Start();
        while (t.IsAlive) {
            Console.WriteLine("Still waiting. I"m going back to sleep.");
            Thread.Sleep(200);
        }
        Console.WriteLine(t.ThreadState);
    }
}


Thread.IsBackground

  
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
public class Form1 : System.Windows.Forms.Form {
    private System.Windows.Forms.ProgressBar progressBar1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private Thread fThread = null;
    private System.ruponentModel.Container components = null;
    public Form1() {
        this.progressBar1 = new System.Windows.Forms.ProgressBar();
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        this.progressBar1.Location = new System.Drawing.Point(24, 32);
        this.progressBar1.Name = "progressBar1";
        this.progressBar1.Size = new System.Drawing.Size(264, 23);
        this.progressBar1.TabIndex = 0;
        this.button1.Location = new System.Drawing.Point(24, 80);
        this.button1.Size = new System.Drawing.Size(136, 40);
        this.button1.Text = "Start Thread";
        this.button1.Click += new
             System.EventHandler(this.button1_Click);
        this.button2.Location = new System.Drawing.Point(168, 80);
        this.button2.Size = new System.Drawing.Size(120, 40);
        this.button2.Text = "Stop Thread";
        this.button2.Click += new
             System.EventHandler(this.button2_Click);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(704, 429);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
          this.button2,
          this.button1,
          this.progressBar1});
        this.ResumeLayout(false);
    }
    protected override void Dispose(bool disposing) {
        if (fThread != null) {
            fThread.Interrupt();
            fThread = null;
        }
    }
    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }
    private void UpdateProgress() {
        if (progressBar1.Value == progressBar1.Maximum) {
            progressBar1.Value = progressBar1.Minimum;
        }
        progressBar1.PerformStep();
    }

    public void ThreadProc() {
        try {
            MethodInvoker mi = new MethodInvoker(this.UpdateProgress);
            while (true) {
                this.BeginInvoke(mi);
                Thread.Sleep(500);
            }
        } catch (ThreadInterruptedException e) {
            Console.WriteLine(
              "Interruption Exception in Thread: {0}",
                  e);
        } catch (Exception we) {
            Console.WriteLine("Exception in Thread: {0}", we);
        }
    }
    private void button1_Click(object sender, System.EventArgs e) {
        fThread = new Thread(new ThreadStart(ThreadProc));
        fThread.IsBackground = true;
        fThread.Start();
    }
    private void button2_Click(object sender, System.EventArgs e) {
        fThread.Interrupt();
        fThread = null;
    }
}


Thread.Join()

  
using System;
using System.Threading;
   
class Sum {
    public Sum(int op1, int op2) {
        Console.WriteLine("[Sum.Sum] Instantiated with values of {0} and {1}", op1, op2);
        this.op1 = op1;
        this.op2 = op2;
    }
    int op1;
    int op2;
    int result;
    public int Result{ get { return result; } }
   
    public void Add()
    {
        Thread.Sleep(5000);
        result = op1 + op2;
    }
}
   
class ThreadData {
    static void Main() {
        Sum sum = new Sum(6, 42);
   
        Thread thread = new Thread(new ThreadStart(sum.Add));
        thread.Start();
   
        for (int i = 0; i < 10; i++) {
            Thread.Sleep(200);
            Console.Write(".");
        }
        thread.Join();
   
        Console.WriteLine("[Main] The result is {0}", sum.Result);
        Console.ReadLine();
    }
}


Thread.ResetAbort()

  
using System; 
using System.Threading; 
 
class MyThread {  
  public Thread thrd;  
    
  public MyThread(string name) {  
    thrd = new Thread(this.run); 
    thrd.Name = name; 
    thrd.Start();  
  }  
  
  void run() {  
    Console.WriteLine(thrd.Name + " starting."); 
 
    for(int i = 1; i <= 100; i++) {  
      try { 
        Console.Write(i + " ");  
        Thread.Sleep(50); 
      } catch(ThreadAbortException exc) { 
        if((int)exc.ExceptionState == 0) { 
          Console.WriteLine("Abort Cancelled! Code is " + exc.ExceptionState); 
          Thread.ResetAbort(); 
        } else  
          Console.WriteLine("Thread aborting, code is " + exc.ExceptionState); 
      } 
    } 
    Console.WriteLine(thrd.Name + " exiting normally.");  
  } 
} 
  
class MainClass {  
  public static void Main() {  
    MyThread mt1 = new MyThread("My Thread");  
 
    Thread.Sleep(1000); 
 
    Console.WriteLine("Stopping thread.");  
    mt1.thrd.Abort(100); 
 
    mt1.thrd.Join(); 
 
    Console.WriteLine("Main thread terminating.");  
  }  
}


Thread.SetData

  
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.rupilerServices;
using System.Security;
using System.Text;
using System.Threading;
public class MainClass
{
    public static void Main()
    {
        LocalDataStoreSlot slot = Thread.AllocateDataSlot();
        Thread.SetData(slot, 63);
        int slotValue1 = (int)Thread.GetData(slot);
        Console.WriteLine(slotValue1);
    }
}


Thread.Sleep

  

 
using System; 
using System.Threading; 
 
class MyThread { 
  public int count; 
  public Thread thrd; 
 
  public MyThread(string name) { 
    count = 0; 
    thrd = new Thread(this.run); 
    thrd.Name = name; 
    thrd.Start(); 
  } 
 
  void run() { 
    Console.WriteLine(thrd.Name + " starting."); 
 
    do { 
      Thread.Sleep(500); 
      Console.WriteLine("In " + thrd.Name + 
                        ", count is " + count); 
      count++; 
    } while(count < 10); 
 
    Console.WriteLine(thrd.Name + " terminating."); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Console.WriteLine("Main thread starting."); 
 
    MyThread mt1 = new MyThread("Child #1"); 
    MyThread mt2 = new MyThread("Child #2"); 
    MyThread mt3 = new MyThread("Child #3"); 
 
    Thread.Sleep(10000); 
 
    Console.WriteLine("Main thread ending."); 
  } 
}


Thread.ThreadState

  
using System;
using System.Threading;
class MainClass
{
  static void MyThreadProc()
  {
    Thread.CurrentThread.Name = "TheSecondaryThread";
    Thread secondaryThread = Thread.CurrentThread;
    Console.WriteLine("Name? {0}", secondaryThread.Name);
    Console.WriteLine("Alive? {0}", secondaryThread.IsAlive);
    Console.WriteLine("Priority? {0}", secondaryThread.Priority);      
    Console.WriteLine("State? {0}", secondaryThread.ThreadState);
    Console.WriteLine();
    for(int i = 0; i < 1000; i ++)
    {
      Console.WriteLine("Value of i is: {0}", i);
      Thread.Sleep(5);
    }
  }
  [MTAThread]
  static void Main(string[] args)
  {
    Thread secondaryThread = new Thread(new ThreadStart(MyThreadProc));
    secondaryThread.Priority = ThreadPriority.Highest;
    
    secondaryThread.IsBackground = true;
    secondaryThread.Start();
  }
}