.net 3.5 suspend

jerry_zhang99 2010-03-05 10:52:42
在.net 3.5中,Thread.suspend() 和 Thread.Resume()被弃用了,请问一下都用什么来挂起和释放线程呢
...全文
70 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jerry_zhang99 2010-03-10
  • 打赏
  • 举报
回复
引用 1 楼 xray2005 的回复:
LZ学习以下《操作系统》。

我是不知道用那个更合适,所以,问了下,最后我用的是 ManualResetEvent,还是不错,挺好用的。谢谢
xingyuebuyu 2010-03-05
  • 打赏
  • 举报
回复
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.html
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);
}
}
}
}


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);
}
}
}
}
xray2005 2010-03-05
  • 打赏
  • 举报
回复
LZ学习以下《操作系统》。


110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧