加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C#中隐式停止对象中的线程

发布时间:2020-12-15 08:46:06 所属栏目:百科 来源:网络整理
导读:我有一个包含工作线程的对象.我想在对象超出范围时杀死线程. using System.IO;using System;using System.Threading;namespace tt { class Program { static void Main() { AnotherClass a = new AnotherClass(); a.Say(); } } class AnotherClass:IDisposab
我有一个包含工作线程的对象.我想在对象超出范围时杀死线程.
using System.IO;
using System;
using System.Threading;

namespace tt {
    class Program
    {
        static void Main()
        {
            AnotherClass a = new AnotherClass();
            a.Say();
        }

    }

    class AnotherClass:IDisposable {
        private bool m_Disposed;
        private readonly AutoResetEvent m_ResetEvent = new AutoResetEvent(false);

        public AnotherClass() {
            Thread t = new Thread(wait);
            t.Start();
        }

        public void Dispose() {
            Dispose(true);
        }
        private void Dispose(bool disposing) {
            if (m_Disposed) {
                return;
            }

            if (disposing) {
                Console.WriteLine("inner disposing");
            }
            m_ResetEvent.Set();
            Console.WriteLine("Outer disposing");
            m_Disposed = true;
        }

        private void wait() {
            m_ResetEvent.WaitOne();
        }

        ~AnotherClass() {
            Dispose(false);
        }

        public void Say() {
            Console.WriteLine("HellO");
        }
    }
}

该程序将挂在那里,因为没有调用AnotherClass的析构函数.我知道我可以调用a.Dispose()来杀死线程.但有没有办法在对象超出范围时隐式杀死线程?

解决方法

不,那是不可能的.没有引用计数可以注意到该对象没有更多引用,因此在发生这种情况时无法执行任何操作.

IDisposable接口用于在不再使用实例时需要执行某些操作的类,并且调用Dispose方法是您发信号通知实例的方式.

在离开作用域时确保放置对象的常用方法是将代码包装在using块中:

static void Main()
{
  using (AnotherClass a = new AnotherClass())
  {
    a.Say();
  }
}

使用块是语法糖尝试…最后块:

static void Main()
{
  AnotherClass a = new AnotherClass();
  try
  {
    a.Say();
  }
  finally
  {
    if (a != null)
    {
      ((Idisposable)a).Dispose();
    }
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读