【问题标题】:What is the best way to handle a thread from a different thread?处理来自不同线程的线程的最佳方法是什么?
【发布时间】:2019-11-29 07:34:16
【问题描述】:

我的要求是处理来自不同线程的线程。我可以使用thread.Suspend()thread.Resume()thread.Abort(),但我收到警告,例如这些方法已被弃用。这些方法是否有任何替代方法,我创建了一个类似于我的应用程序的虚拟控制台应用程序,请帮助解决这个问题。 下面是我的代码

using System;
using System.Threading;

namespace ThreadingTest
{
    internal class Program
    {
        private static Thread mainThread;

        private static void Main(string[] args)
        {
            mainThread = Thread.CurrentThread;

            Thread connectServerThread = new Thread(new ThreadStart(ConnectServer));
            connectServerThread.Start();

            int i = 0;
            while (true)
            {
                if (i++ % 5000 == 0)
                {
                    Console.WriteLine(i);
                }
            }
        }

        private static void ConnectServer()
        {
            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(2000);
                if (i % 2 == 0)
                {
                    mainThread.Suspend();
                }
                else
                {
                    mainThread.Resume();
                }
            }
            mainThread.Abort();
        }
    }
}

【问题讨论】:

  • 您应该只向线程发送请求,并让线程(代码)自行管理如何处理该请求。如果线程只是将数据写入文件并且您挂起或中止它怎么办?最终会导致数据损坏。
  • 但在我的情况下,我必须执行 500 个步骤或代码行,如果我设置了一个标志,那么在每个步骤中我都需要检查该标志,这对我来说是不可行的。
  • @SirRufo 它是一个虚拟应用程序,不是实际应用程序,它的实现不同
  • 我说的是一般的线程/任务

标签: c# multithreading thread-safety


【解决方案1】:

我会听从documentation中的建议

不要使用 Suspend 和 Resume 方法来同步线程的活动。当您挂起线程时,您无法知道线程正在执行什么代码。如果在安全权限评估期间挂起一个线程而它持有锁,则 AppDomain 中的其他线程可能会被阻止。如果在执行类构造函数时挂起线程,则 AppDomain 中尝试使用该类的其他线程将被阻止。死锁很容易发生。

更具体地说,警告提供的建议:

请使用 System.Threading 中的其他类,例如 Monitor、Mutex、Event 和 Semaphore,以同步线程或保护资源

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2013-10-23
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多