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); 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!");
  }
} 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);
} 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 ('?');
} 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; }
    }
  }
} 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; }
}
 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; }
} 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");
} 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控件与线程调用:

 


delegate void thread_end_sync(paramType,param);
void sync_method(paramType,param)
{
	//将param用于 winform控件刷新

	.......//线程处理
      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控件刷新
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值