c# 线程入门

1. 线程入门,参考原文: threading


C# supports parallel execution of code through multithreading. A thread is an independent execution path, able to run simultaneously with other threads.


线程创建,线程的两个重载的构造函数

public delegate void ThreadStart();
public delegate void ParameterizedThreadStart (object obj);

class ThreadTest
{
  static void Main() 
  {
    Thread t = new Thread (new ThreadStart (Go));
 
    t.Start();   // Run Go() on the new thread.
    Go();        // Simultaneously run Go() in the main thread.
  }
 
  static void Go()
  {
    Console.WriteLine ("hello!");
  }
}

 线程传参


static void Main()
{
  Thread t = new Thread (new ParameterizedThreadStart(Print));//create a thread
  t.Start ("Hello from t!");
}
 
static void Print (object messageObj)
{
  string message = (string) messageObj;   // We need to cast here
  Console.WriteLine (message);
}

线程安全。


The CLR assigns each thread its own memory stack so that local variables are kept separate. In the next example, we define a method with a local variable, then call the method simultaneously on the main thread and a newly created thread:

static void Main() 
{
  new Thread (Go).Start();      // Call Go() on a new thread
  Go();                         // Call Go() on the main thread
}
 
static void Go()
{
  // Declare and use a local variable - 'cycles'
  for (int cycles = 0; cycles < 5; cycles++) Console.Write ('?');
}

A separate copy of the cycles variable is created on each thread's memory stack, and so the output is, predictably, ten question marks.

Threads share data if they have a common reference to the same object instance.

线程加锁。

The remedy is to obtain an exclusive lock while reading and writing to the common field. C# provides the lockstatement for just this purpose:

class ThreadSafe 
{
  static bool done;
  static readonly object locker = new object();
 
  static void Main()
  {
    new Thread (Go).Start();
    Go();
  }
 
  static void Go()
  {
    lock (locker)
    {
      if (!done) { Console.WriteLine ("Done"); done = true; }
    }
  }
}

When two threads simultaneously contend a lock (in this case, locker), one thread waits, or blocks, until the lock becomes available. In this case, it ensures only one thread can enter the critical section of code at a time, and “Done” will be printed just once. Code that's protected in such a manner — from indeterminacy in a multithreading context — is called thread-safe.

何时加锁:

As a basic rule, you need to lock around accessing any writable shared field

class ThreadUnsafe
{
  static int _x;
  static void Increment() { _x++; }
  static void Assign()    { _x = 123; }
}

Here are thread-safe versions 

class ThreadSafe
{
  static readonly object _locker = new object();
  static int _x;
 
  static void Increment() { lock (_locker) _x++; }
  static void Assign()    { lock (_locker) _x = 123; }
}


线程等待

You can wait for another thread to end by calling its Join method. For example:

static void Main()
{
  Thread t = new Thread (Go);
  t.Start();
  t.Join();//等待t线程结束
  Console.WriteLine ("Thread t has ended!");// t线程 结束后,执行main线程。
}
 
static void Go()
{
  for (int i = 0; i < 1000; i++) Console.Write ("y");
}

winForm控件与线程调用:

void t_thread(object  st)
{
	.......//线程处理
      this.invoke(new thread_end_sync(this.sync_method),param);//param --用于winform控件刷新的参数
}
delegate void thread_end_sync(paramType,param);
void sync_method(paramType,param)
{
	//将param用于 winform控件刷新
}
 
 

猜你喜欢

转载自blog.csdn.net/sophiemantela/article/details/78720053