在.net 3.5中,Thread.suspend() 和 Thread.Resume()被弃用了,请问一下都用什么来挂起和释放线程呢

解决方案 »

  1.   

    Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. (请使用System.Threading中的其他类,如Monitor, Mutex, Event, 和Semaphore,以同步线程和保护资源。) Thread.Suspend和Thread.Resume被废弃的主要原因是因为其使用很容易造成线程死锁(Deadlock)。http://www.blogjava.net/fhtdy2004/archive/2009/06/10/281315.htmlusing System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;namespace ConsoleApplication18
    {
    class Program
    {
    static void Main(string[] args)
    {
    AutoResetEvent waitHandle = new AutoResetEvent(false);//start other thread
    Worker worker = new Worker();
    worker.DoSomeWork(waitHandle);//let main UI thread so some processing
    Console.WriteLine("Main thread working");
    Thread.Sleep(5000);Console.WriteLine("Main thread finished work, let other thread
    continue");
    waitHandle.Set();Console.ReadLine();
    }
    }class Worker
    {
    private WaitHandle waitHandle;public void DoSomeWork(WaitHandle waitHandle)
    {
    this.waitHandle = waitHandle;Thread t = new Thread(new ThreadStart(ProcessValues));
    t.Start();
    }private void ProcessValues()
    {
    //Can run this anytime
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("processing:" + i);
    }//make sure I am allowed to keep going
    this.waitHandle.WaitOne();//Can only run this once main thread is happy
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("last processing:" + i);
    }
    }
    }
    }
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;namespace ConsoleApplication18
    {
    class Program
    {
    static void Main(string[] args)
    {
    AutoResetEvent waitHandle = new AutoResetEvent(false);//start other thread
    Worker worker = new Worker();
    worker.DoSomeWork(waitHandle);//let main UI thread so some processing
    Console.WriteLine("Main thread working");
    Thread.Sleep(5000);Console.WriteLine("Main thread finished work, let other thread
    continue");
    waitHandle.Set();Console.ReadLine();
    }
    }class Worker
    {
    private WaitHandle waitHandle;public void DoSomeWork(WaitHandle waitHandle)
    {
    this.waitHandle = waitHandle;Thread t = new Thread(new ThreadStart(ProcessValues));
    t.Start();
    }private void ProcessValues()
    {
    //Can run this anytime
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("processing:" + i);
    }//make sure I am allowed to keep going
    this.waitHandle.WaitOne();//Can only run this once main thread is happy
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("last processing:" + i);
    }
    }
    }
    }
      

  2.   

    我是不知道用那个更合适,所以,问了下,最后我用的是 ManualResetEvent,还是不错,挺好用的。谢谢