有什么其他办法挂起和恢复线程? [英] What are alternative ways to suspend and resume a thread?

查看:390
本文介绍了有什么其他办法挂起和恢复线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法 Thread.Suspend() Thread.Resume()是因为.NET 2.0过时。为什么?有什么其他的替代品和任何的例子?

The two methods Thread.Suspend() and Thread.Resume() are obsolete since .NET 2.0. Why? What are other alternatives and any examples?

推荐答案

您会希望使用的AutoResetEvent的EventWaitHandle。

You'll want to use an AutoResetEvent EventWaitHandle.

假设你想要做这样的事情(注意:不这样做!):

Say you want to do something like this (NOTE: don't do this!):

private Thread myThread;

private void WorkerThread() 
{
    myThread = Thread.CurrentThread;
    while (true)
    {
        myThread.Suspend();
        //Do work.
    }
}

public void StartWorking() 
{
    myThread.Resume();
}

像其他人所说,这是一个坏主意。即使只使用挂​​起自己的线程是比较安全的,你永远无法弄清楚,如果你调用恢复当线程实际上是暂停。因此,挂起和恢复已过时。

Like others have said, this is a bad idea. Even though only using Suspend on its own thread is relatively safe, you can never figure out if you're calling Resume when the thread is actually suspended. So Suspend and Resume have been obsoleted.

相反,你要使用的AutoResetEvent:

Instead, you want to use an AutoResetEvent:

private EventWaitHandle wh = new AutoResetEvent();

private void WorkerThread() 
{
    while(true) 
    {
        wh.WaitOne();
        //Do work.
    }
}

public void StartWorking()
{
    wh.Set();
}

工作线程将等待在等待手柄,直到另一个线程调用StartWorking。它的工作原理大致相同挂起/恢复,为的AutoResetEvent只允许一个线程是恢复。

The worker thread will wait on the wait handle until another thread calls StartWorking. It works much the same as Suspend/Resume, as the AutoResetEvent only allows one thread to be "resumed".

这篇关于有什么其他办法挂起和恢复线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆