首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Thread.Suspend()已过时

Thread.Suspend()已过时
EN

Stack Overflow用户
提问于 2017-02-28 21:55:14
回答 1查看 489关注 0票数 1

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

所以,我尝试使用ThreadC.Suspend(),错误消失了,但是挂起的方法已经过时了。我怎么才能修复它?

代码语言:javascript
复制
    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);
            }
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2017-02-28 22:13:54

1:使用"Assert.Fail()“代替Assert.IsTrue(false);

2:如果使用过时的方法,请阅读Microsoft文档。“Thread.Suspend已被弃用。请使用System.Threading中的其他类,如监视器、互斥锁、事件和信号量,以同步线程或保护资源。”

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等待所有任务,而不是使用线程

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42510629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档