【问题标题】:Thread.Suspend() is obsoleteThread.Suspend() 已过时
【发布时间】:2017-02-28 13:55:14
【问题描述】:

我的线程有问题,我想创建n个线程并写一个日志(带有方法write,已经实现) 这是一个单元测试,当我运行它时,它运行良好,但出现异常: System.AppDomainUnloadedException:试图访问已卸载的 AppDomain。如果测试启动了一个线程但没有停止它,就会发生这种情况。确保测试启动的所有线程在完成之前都已停止。

所以,我尝试使用 ThreadC.Suspend() 并且错误消失了,但是方法 Suspend 已过时.. 我该如何解决?

    public void TestMethod1()
    {
        try
        {
            LogTest logTest = new LogTest(new FileLog());
            logTest.PerformanceTest();

            logTest = new LogTest(new CLogApi());
            logTest.PerformanceTest();

            logTest = new LogTest(new EmptyLog());
            logTest.PerformanceTest();
        }
        catch (Exception)
        {
            Assert.IsTrue(false);
        }
    }

    public class LogTest
    {

        private readonly Log log;


        private int numberOfIterations = 5;


        public LogTest(Log log)
        {
            this.log = log;
        }

        public void PerformanceTest()
        {
            for (int i = 0; i < this.numberOfIterations; i++)
            {
                try
                {
                    Thread threadC = Thread.CurrentThread;
                    threadC = new Thread(this.ThreadProc);
                    threadC.Name = i.ToString();
                    threadC.Start();
                //    threadC.IsBackground = true;
                }
                catch (Exception)
                {
                    Assert.IsTrue(false);
                }
            }
        }

            private void ThreadProc()
            {
            try
            {
                this.log.Write(" Thread : " + Thread.CurrentThread.Name.ToString());
                this.log.Write(" Thread : " + Thread.CurrentThread.Name.ToString());
                this.log.Write(" Thread : " + Thread.CurrentThread.Name.ToString());
                this.log.Write(" Thread : " + Thread.CurrentThread.Name.ToString());


            }
            catch (Exception)
            {
                Assert.IsTrue(false);
            }
        }
    }

【问题讨论】:

  • 你不能。不要使用大锤解决方案,使用 AutoResetEvent。在 ThreadProc() 结束时调用它的 Set() 方法,在 Start() 调用之后调用它的 WaitOne() 方法。

标签: c# .net multithreading suspend


【解决方案1】:

1: 你应该使用 "Assert.Fail()" 而不是 Assert.IsTrue(false);

2:如果您使用过时的方法,请阅读 Microsoft 文档。他们写了你可以使用的东西。“Thread.Suspend 已被弃用。请使用 System.Threading 中的其他类,例如 Monitor、Mutex、Event 和 Semaphore,以同步线程或保护资源。”

3:如果我理解正确,您想杀死所有正在运行的线程或等待它们。您可以使用“Thread.Join()”https://msdn.microsoft.com/de-de/library/95hbf2ta(v=vs.110).aspx 您可以将所有线程存储在一个数组中,也可以在最后列出一个连接所有线程。

4:您可以使用异步模式代替线程,并通过 Task.WaitAll(tasks) https://msdn.microsoft.com/en-us/library/dd270695(v=vs.110).aspx 等待所有任务

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2011-04-26
    相关资源
    最近更新 更多