C# Threading.Suspend 已过时,线程已被弃用?

发布于 2024-10-08 18:48:49 字数 2527 浏览 4 评论 0原文

在我的应用程序中,我正在通过另一个线程(GUI 线程除外)执行文件读取。有两个按钮分别用于暂停和恢复线程。

private void BtnStopAutoUpd_Click(object sender, EventArgs e) 
{
    autoReadThread.Suspend();
}

private void BtnStartAutoUpd_Click(object sender, EventArgs e) 
{
    autoReadThread.Resume();
}

但我面临这个警告,

Thread.Suspend 已被弃用。请使用System.Threading中的其他类,例如Monitor、Mutex、Event和Semaphore来同步线程或保护资源。 http://go.microsoft.com/fwlink/?linkid=14202< /p>

无论如何,我只运行一个线程(而不是GUI线程),那么我如何在这里应用同步或监视。

更新代码:

class ThreadClass 
{

    // This delegate enables asynchronous calls for setting the text property on a rich text box control.
    delegate void UpdateTextCallback(object text);

    // create thread that perform actual task
    public Thread autoReadThread = null;

    public ManualResetEvent _event = new ManualResetEvent(true);

    // a new reference to rich text box
    System.Windows.Forms.RichTextBox Textbox = null;

    private volatile bool _run;

    public bool Run 
    {
        get 
        {
            return _run;
        }
        set 
        {
            _run = value;
        }
    }

    public ThreadClass(string name, System.Windows.Forms.RichTextBox r1) 
    {
        Textbox = r1;
        Run = true;
        this.autoReadThread = new Thread(
            new ParameterizedThreadStart(UpdateText));
        
        this.autoReadThread.Start(name);
    }

    private void UpdateText(object fileName) 
    {
        //while (true)
        //{
        //    _event.WaitOne();
        //}
        while (Run) 
        {

            if (Textbox.InvokeRequired) 
            {
                UpdateTextCallback back = new UpdateTextCallback(UpdateText);
                
                Textbox.BeginInvoke(back, new object[] {
                        fileName
                     });
                     
                Thread.Sleep(1000);
            } 
            else 
            {
                string fileToUpdate = (string) fileName;
                using(StreamReader readerStream = new StreamReader(fileToUpdate)) 
                {
                    Textbox.Text = readerStream.ReadToEnd();
                }
                
                break;
            }
        }
    }

}

运行是 bool 值,一个线程控制它(最初是 true)

并启动一个线程,我在另一个类中创建这个类实例(也是这个启动线程)

In my application, I am performing my file reading by another thread(other than the GUI thread). There are two buttons that suspend and resume the Thread respectively.

private void BtnStopAutoUpd_Click(object sender, EventArgs e) 
{
    autoReadThread.Suspend();
}

private void BtnStartAutoUpd_Click(object sender, EventArgs e) 
{
    autoReadThread.Resume();
}

but I am facing this warning,

Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202

Anyhow, I run only a single thread (rather than a GUI thread), so How can I apply Synchronization here or monitor.

Update Code:

class ThreadClass 
{

    // This delegate enables asynchronous calls for setting the text property on a rich text box control.
    delegate void UpdateTextCallback(object text);

    // create thread that perform actual task
    public Thread autoReadThread = null;

    public ManualResetEvent _event = new ManualResetEvent(true);

    // a new reference to rich text box
    System.Windows.Forms.RichTextBox Textbox = null;

    private volatile bool _run;

    public bool Run 
    {
        get 
        {
            return _run;
        }
        set 
        {
            _run = value;
        }
    }

    public ThreadClass(string name, System.Windows.Forms.RichTextBox r1) 
    {
        Textbox = r1;
        Run = true;
        this.autoReadThread = new Thread(
            new ParameterizedThreadStart(UpdateText));
        
        this.autoReadThread.Start(name);
    }

    private void UpdateText(object fileName) 
    {
        //while (true)
        //{
        //    _event.WaitOne();
        //}
        while (Run) 
        {

            if (Textbox.InvokeRequired) 
            {
                UpdateTextCallback back = new UpdateTextCallback(UpdateText);
                
                Textbox.BeginInvoke(back, new object[] {
                        fileName
                     });
                     
                Thread.Sleep(1000);
            } 
            else 
            {
                string fileToUpdate = (string) fileName;
                using(StreamReader readerStream = new StreamReader(fileToUpdate)) 
                {
                    Textbox.Text = readerStream.ReadToEnd();
                }
                
                break;
            }
        }
    }

}

the run is bool value, a thread controls it(Initially it's true)

and to start a thread I am creating this class instance(this start thread also) in another class

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光病人 2024-10-15 18:48:49
 //true makes the thread start as "running", false makes it wait on _event.Set()
  ManualResetEvent _event = new ManualResetEvent(true); 
  Thread _thread = new Thread(ThreadFunc);

  public void ThreadFunc(object state)
  {
      while (true)
      {
          _event.Wait();

          //do operations here
      }
  }


  _thread.Start();

  // to suspend thread.
  _event.Reset();

  //to resume thread
  _event.Set();

注意,所有操作都在线程“挂起”之前完成

你想要的

private void ThreadFunc(object fileName)
{
    string fileToUpdate = (string)fileName;
    while (Run)
    {
        _event.WaitOne(); 

        string data;
        using (StreamReader readerStream = new StreamReader(fileToUpdate))
        {
            data = readerStream.ReadToEnd();
        }

        if (Textbox.InvokeRequired)
        {
            UpdateTextCallback back = new UpdateTextCallback(UpdateText);
            Textbox.BeginInvoke(back, new object[] { data });
        }

                Thread.Sleep(1000); 
    }       
}


private void UpdateText(string data)
{
    Textbox.Text = data;
}
 //true makes the thread start as "running", false makes it wait on _event.Set()
  ManualResetEvent _event = new ManualResetEvent(true); 
  Thread _thread = new Thread(ThreadFunc);

  public void ThreadFunc(object state)
  {
      while (true)
      {
          _event.Wait();

          //do operations here
      }
  }


  _thread.Start();

  // to suspend thread.
  _event.Reset();

  //to resume thread
  _event.Set();

Note that all operations are completed before the thread is "suspended"

What you want

private void ThreadFunc(object fileName)
{
    string fileToUpdate = (string)fileName;
    while (Run)
    {
        _event.WaitOne(); 

        string data;
        using (StreamReader readerStream = new StreamReader(fileToUpdate))
        {
            data = readerStream.ReadToEnd();
        }

        if (Textbox.InvokeRequired)
        {
            UpdateTextCallback back = new UpdateTextCallback(UpdateText);
            Textbox.BeginInvoke(back, new object[] { data });
        }

                Thread.Sleep(1000); 
    }       
}


private void UpdateText(string data)
{
    Textbox.Text = data;
}
凯凯我们等你回来 2024-10-15 18:48:49

不推荐使用挂起和恢复的原因是因为无法保证线程将在执行的哪个点挂起。这是一件坏事。该问题已描述这里以及解决方案。

该解决方案应该涉及一个 WaitHandle(可能是 AutoResetEvent 或 ManualResetEvent),您可以使用它向 autoReadThread 发出停止/启动信号。

The reason Suspend and Resume are deprecated is because there are no guarantees at what point in the execution the thread will be suspended on. This is a bad thing. The issue is described here as well as a solution.

The solution should involved a WaitHandle (maybe AutoResetEvent or ManualResetEvent) which you can use to signal to your autoReadThread to stop/start.

话少心凉 2024-10-15 18:48:49

我将使用监视器机制来实现暂停和恢复线程。 Monitor.Wait 将导致线程等待 Monitor.Pulse。

private bool _pause = false;
private object _threadLock = new object();

private void RunThread()
{
    while (true)
    {
        if (_pause)
        {
            lock (_threadLock)
            {
                Monitor.Wait(_threadLock);
            }
        }

        // Do work
    }
}

private void PauseThread()
{
    _pause = true;
}

private void ResumeThread()
{
    _pause = false;
    lock (_threadLock)
    {
        Monitor.Pulse(_threadLock);
    }
}

I would use the Monitor mechanism for achieving pausing and resuming threads. The Monitor.Wait will cause the thread to wait for the Monitor.Pulse.

private bool _pause = false;
private object _threadLock = new object();

private void RunThread()
{
    while (true)
    {
        if (_pause)
        {
            lock (_threadLock)
            {
                Monitor.Wait(_threadLock);
            }
        }

        // Do work
    }
}

private void PauseThread()
{
    _pause = true;
}

private void ResumeThread()
{
    _pause = false;
    lock (_threadLock)
    {
        Monitor.Pulse(_threadLock);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文