我现在有一个多线程程序,
每当我不想再执行的时候,关闭掉网页
可是 w3wp.exe这进程还占用50%的CPU。
如何关闭网页的时候还能继续执行页面的后台代码?
或者就是关闭网页就释放服务器资源。
 Thread workThread, caculateThread;
        List<int> returnValue = new List<int>();
        int flag;
        DateTime beginTime, executeTime;        private int Flag
        {
            get { return flag; }
        }        protected void Page_Load(object sender, EventArgs e)
        {        }        protected void btnCreate_Click(object sender, EventArgs e)
        {
            List<int> data = MainWork();
            int state = Flag;            if (state == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "123", "<script type=\"text/javascript\">alert(\"报表生成成功~!\")</script>");            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "123", "<script type=\"text/javascript\">alert(\"报表生成超时~!\")</script>");
            }
        }        private void caculateTime()
        {
            executeTime = DateTime.Now;
            Thread.Sleep(10 * 1000);
            caculateTime();
        }        private void TemplateWork()
        {
            for (int i = 0; i < 10; i++)
            {
                returnValue.Add(i);
            }            Thread.Sleep(2 * 60 * 1000);
            flag = 1;
        }        private List<int> MainWork()
        {
            workThread = new Thread(new ThreadStart(TemplateWork));
            caculateThread = new Thread(caculateTime);            beginTime = executeTime = DateTime.Now;            flag = 0;            workThread.IsBackground = true;
            workThread.Start();
            caculateThread.IsBackground = true;
            caculateThread.Start();            while (workThread.IsAlive)
            {
                if (beginTime.AddMinutes(Convert.ToDouble(this.txtExecuteTime.Text.ToString())) < executeTime)
                {
                    workThread.Abort();
                    caculateThread.Abort();
                    flag = 2;
                    return null;
                }
            }            if (caculateThread.IsAlive)
            {
                caculateThread.Abort();
            }            return returnValue;
        }
我把我代码贴上来了,
也就是如何当关闭网页的时候,还能去执行workThread.abort()和caculateThread.abort();

解决方案 »

  1.   


      protected void Session_End(object sender, EventArgs e)
            {
                Cache cache = new Cache();
                Thread work = cache.Get("work") as Thread;
                if (work.IsAlive)
                {
                    work.Abort();
                }            Thread caculate = cache.Get("caculate") as Thread;            if (caculate.IsAlive)
                {
                    caculate.Abort();
                }
            }        protected void Application_End(object sender, EventArgs e)
            {
                Cache cache = new Cache();
                Thread work = cache.Get("work") as Thread;
                if (work.IsAlive)
                {
                    work.Abort();
                }            Thread caculate = cache.Get("caculate") as Thread;            if (caculate.IsAlive)
                {
                    caculate.Abort();
                }
            }写在这两个处理函数里面都不起作用的,单步都进不去,奇怪
      

  2.   

    你在web页面里面开线程
    这个线程没人去结束,当然占cpu了
      

  3.   

    执行Session.Abandon()后,客户端必须至少有一次请求,才能正确反应Session的状态。  
    Session_End是被动触发
    关闭调用windows服务,或WINFORM程序关闭进程或通过AJAX调用关闭进程
      

  4.   

    1.添加JS事件  onunload="fun()"
    fun() 调用AJAX,去后台 终止线程
    另:session_end 事件 不是在关闭网页 就立马调用,而是有个Sessiontimeout 到这个期限 才会调用不会及时释放
      

  5.   

    杯具,搞来搞去最终还是到了ajax.
      

  6.   

    你这个 用法 真囧在Page 里 新开启线程如果有十个用户 进入此页面 就开 10个线程强制关闭网页等方式的话,可能会无法关闭。
      

  7.   

    没办法,不然还能用什么方法。AJAX用的话也需要多线程吧,
    再说AJAX不熟悉,
      

  8.   

    用个静态的 键值对 diectory 对象,sessionid 作为唯一键,thread对象为 值来静态存储 thread对象
    后面 你就在 你的session_end里 调用释放当前的sessionid 的thread对象
      

  9.   

    可是这个sessiontimeout时间太长了,
    要是十几分钟的话,我程序都已经自动 释放了 资源 了。
    我就是想关闭网页的时候就把这两个进程干掉。
      

  10.   

      $.ajax({
                    url: 'ajax/test.html',
                    success: function (data) {
                        $('.result').html(data);
                        alert('Load was performed.');
                    }
                });ajax的这个可以试一试,可是这里的参数是要给一个url,需要的是一个page,而我终止进程是写在当前page里的方法里面,这咋整
      

  11.   

    用URL的方式 会产生新的 线程。。
      

  12.   

    不理解,能否把thread存到dictionary,然后另外一个页面结束dictionary里的两个进程,给我一个简单的例子
      

  13.   

     我的文章采集功能也有这样的困扰。我想了几小时,突然来了灵感。启动线程的时候,开启一个时效较短的HttpRuntime.Cache--子线程可以访问得到HttpRuntime.Cache。前台用ajax更新HttpRuntime.Cache,保持它不过期。一但关闭了网页HttpRuntime.Cache没多久就过期,线程就知道以后就停止任务了。
      

  14.   

    能否给个例子,httpruntime.cache默认过期时间是多久。?
      

  15.   

    页面用ajax每隔1秒发送信息给服务器,服务器如果收不到信息,就算下线,自动终止。线程里面每执行一个小任务就判断一下状态。
      

  16.   

    1.进入页面 利用以下方式进行保存
    static dictionary<string,thread> d=new dictionary<string,thread> ();dictionary["sessionid"]=thread;
    2.退出时 调用
    删除时 thread t=dictionary["sessionid"];t.abort();以上方法可以放到有一个class中你的代码   Thread work =dictionary["sessionid"] as Thread;
                if (work.IsAlive)
                {
                    work.Abort();
                }            Thread caculate = cache.Get("caculate") as Thread;            if (caculate.IsAlive)
                {
                    caculate.Abort();
                }
      

  17.   

    加入Global.asax文件,然后在
    protected void Session_End(object sender, EventArgs e)
    {}
    方法中写释放线程资源的方法。
      

  18.   

        public class CacheHelper
        {
            /// <summary> 
            /// 缓存时间方式 
            /// </summary> 
            public enum DateTimeType
            {
                /// <summary>
                /// 秒
                /// </summary>
                Second = 1,
                /// <summary> 
                /// 小时 
                /// </summary> 
                Hour = 3600,
                /// <summary> 
                /// 天数 
                /// </summary> 
                Day = 86400,
            }
            /// <summary>
            /// 新增缓存
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="Value"></param>
            /// <param name="datetime"></param>
            public static void Add<T>(string key, T Value, int datetime)
            {
                Add<T>(key, Value, DateTimeType.Second, datetime, null, CacheItemPriority.NotRemovable);
            }
            /// <summary> 
            /// 新增缓存 
            /// </summary> 
            /// <typeparam name="T"> </typeparam> 
            /// <param name="key"> </param> 
            /// <param name="Value"> </param> 
            /// <param name="datetimetype"> </param> 
            /// <param name="datetime"> </param> 
            public static void Add<T>(string key, T Value, DateTimeType datetimetype, int datetime)
            {
                Add<T>(key, Value, datetimetype, datetime, null, CacheItemPriority.NotRemovable);
            }        /// <summary> 
            ///  新增缓存 
            /// </summary> 
            /// <typeparam name="T"> </typeparam> 
            /// <param name="key"> </param> 
            /// <param name="Value"> </param> 
            /// <param name="datetimetype"> </param> 
            /// <param name="datetime"> </param> 
            /// <param name="file"> </param> 
            public static void Add<T>(string key, T Value, DateTimeType datetimetype, int datetime, CacheDependency file)
            {
                Add<T>(key, Value, datetimetype, datetime, file, CacheItemPriority.NotRemovable);
            }        /// <summary> 
            /// 新增缓存 
            /// </summary> 
            /// <typeparam name="T"> </typeparam> 
            /// <param name="key"> </param> 
            /// <param name="Value"> </param> 
            /// <param name="datetimetype"> </param> 
            /// <param name="datetime"> </param> 
            /// <param name="file"> </param> 
            /// <param name="cacheItemPriority"> </param> 
            public static void Add<T>(string key, T Value, DateTimeType datetimetype, int datetime, CacheDependency file, CacheItemPriority cacheItemPriority)
            { 
                double Seconds = datetime * (int)datetimetype;            HttpRuntime.Cache.Add(key, Value, file, DateTime.Now.AddSeconds(Seconds), TimeSpan.Zero, cacheItemPriority, null);
            }         /// <summary> 
            /// 获取缓存 
            /// </summary> 
            /// <typeparam name="T"> </typeparam> 
            /// <param name="key"> </param> 
            /// <returns> </returns> 
            public static T Get<T>(string key)
            {
                return (T)HttpRuntime.Cache.Get(key);
            }
            /// <summary>
            /// 获取缓存 
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            public static bool TryGet<T>(string key, out T value)
            {
                object obj = HttpRuntime.Cache.Get(key);
                if (obj == null)
                {
                    value = default(T);
                    return false;
                }
                else
                {
                    value = (T)obj;
                    return true;
                }
            }
            /// <summary> 
            /// 清空缓存 
            /// </summary> 
            public static void Clear()
            {
                HttpRuntime.Close();
            }        /// <summary> 
            /// 移除缓存 
            /// </summary> 
            /// <param name="key"> </param> 
            public static void Remove(string key)
            {
                try
                {
                    HttpRuntime.Cache.Remove(key);
                }
                catch { }
            }
        }先来段缓存的操作类。CacheHelper.Add("一个已知的id","随便一个值",10);ajax 轮询一个.ashx页面
    里面执行 CacheHelper.Add("一个已知的id","随便一个值",10);多线程里面string str;
    if(CacheHelper.TryGet("一个已知的id",out str) == false)
    {
       结束线程的代码
    }
      

  19.   

    这个不对,ajax 轮询一个.ashx页面
    里面执行 CacheHelper.Add("一个已知的id","随便一个值",10);
    这里轮轮询执行的话,你这个key都重复的,第二次执行到这里的时候肯定加不进去。
      

  20.   

    琐碎的事情太多了,给你提供个思路。你创建一个线程, 用于判断页面是否关闭  (此线程为关键线程)因为页面关闭的判断不好弄,精准的判断只能是 ajax 或服务器长链接你需要使用ajax 的方式, 开启线程的时候  在指定位置写些东西  (指定位置可以是Session)写的东西是 一个标志位和当前操作时间每次 ajax 访问时都更新操作时间线程内需要每隔指定时间判断  指定位置的数据是否过期,通过操作时间判断,操作时间与当前时间查出指定间隔为过期。过期时让线程终止。此线程 还要做的工作是  在此线程内创建你之前创建的工作线程,并让工作线程的 IsBackground 为 true ,这样在关键线程关闭时工作线程也应该会关闭.因为我没实际操作,不好直接断言。
      

  21.   

    的确是个经典案例,如果有个大牛写个demo就太酷了