我想问一个问题 我想放一段死循环程序到 网站里面去 
要怎么弄才能达到以下条件
1.不影响其他使用者 
2.不需要有人去点击页面触发
3.网站运行周期内 ,这段程序都要运行
4.特定网站使用者, 可以影响,操作这段程序

解决方案 »

  1.   

    线程中
    while(true)
    {
    }
      

  2.   

    for(int i=0;i++;i<i+1)
    {}
      

  3.   

    因为要不停的到一个socket里面查值,但是我不想再服务器上面写一个winform跑,
    但是又不想写到页面里面, 然后来一个用户, 跑一个实例 ,我只想从头到尾 整个网站内存里面只跑一个实例
      

  4.   

    1.不影响其他使用者 ->不太可能不影响。除非你自己给网站挂个马。 给指定的用户种马。
    2.不需要有人去点击页面触发->访问一个特定的页面
    3.网站运行周期内 ,这段程序都要运行->最简单网站首页。必经之路
    4.特定网站使用者, 可以影响,操作这段程序->你想多了我觉得别人的机子没死机前,你的服务器已经宕机了。
      

  5.   

    我的需求很简单 就是在web程序里面实现对一个socket接口数据的实时读取,并且不能给接口造成压力
      

  6.   

    global.asax 中写 可以实现你的要求
      

  7.   

    也对啊 实时的话 写个计时器
    global.asax 设定了一个计时器
    void Application_Start(object sender, EventArgs e)
        {
            // 在应用程序启动时运行的代码
            System.Timers.Timer myTimer = new System.Timers.Timer(1000);
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            myTimer.Interval = 1000;
            myTimer.Enabled = true;
        }
      

  8.   

    太简单了
    int i=2;
    while(1>0)
    {
     i=i*i;
    }
      

  9.   


    接收类
    class received 
    {
      event receivedEvent ev; //接收事件
    }主程序
    Main()
    {
      r=new received();//实例接收类
      r.ev+=new receivedEvent(r_received);//绑定事件
    }接收方法
    void r_received()
    {
      接收...
    }
      

  10.   

    可以做成windows服务,使用开源框架 Topshelf
      

  11.   

    一个线程,线程函数包含while(true){//判断用户//接收中断请求}
      

  12.   


    显然你的思想是错误的,或者你对网络协议的了解太少
    使用socket服务编程  用线程监听 做轮询  
      

  13.   


    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Text;
    using System.Threading;
    using System.Net.Sockets;
    using System.Net;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    using System.Data;
    using System.Windows.Forms;
    using System.Configuration;
    using Microsoft.Win32;
    using System.Diagnostics;
    using System.Timers;namespace WSGPSGateway
    {
        public partial class TcpServer : Form
        {
            public TcpServer()
            {
                InitializeComponent();
            }        #region 自定义字段        public static ManualResetEvent allDone = new ManualResetEvent(false);        /// <summary>
            /// 监听控件开启状态
            /// </summary>
            private bool State = true;        /// <summary>
            /// 声明一个线程实例
            /// </summary>
            private Thread mythread;        /// <summary>
            /// 服务器端Ip
            /// </summary>
            private int _port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);        /// <summary>
            /// 保存客户端所有回话的哈希表
            /// </summary>
            private Hashtable _transmit_tb = new Hashtable();        /// <summary>
            /// 用于接受消息的线程
            /// </summary>
            private Thread _receviccethread = null;        public struct TCPParameter
            {
                public string Package;
                public string IpAddress;
            }        #endregion        #region 监听代码块        //窗体运行
            private void TcpServer_Load(object sender, EventArgs e)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Opacity = 0; // 窗体透明度  
                Form.CheckForIllegalCrossThreadCalls = false;
                InitializeComponent();
                mythread = new Thread(Listen);
                mythread.Start();            System.Timers.Timer atimer = new System.Timers.Timer();
                atimer.Elapsed += new System.Timers.ElapsedEventHandler(TimeEvent);
                atimer.Interval = 1000;
                atimer.Enabled = true;
                GC.KeepAlive(atimer); 
            }        private object threadlock = new object();        //启动监听
            private void BtnStart_Click(object sender, EventArgs e)
            {
                //多线程
            }        //启动监听,轮询监听客户机请求并将客户端套接字存入转发表
            private void Listen()
            {
                try
                {
                    IPAddress _ip = IPAddress.Any;
                    Socket newsoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    newsoc.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    IPEndPoint locaEp = new IPEndPoint(IPAddress.Any, _port);//建立连接           
                    newsoc.Bind(locaEp);
                    newsoc.Listen(100);
                    allDone.Reset();
                    newsoc.BeginAccept(new AsyncCallback(onCall), newsoc);//继续接受其他客户端的连接 
                    allDone.WaitOne();
                }
                catch (Exception ex)
                {
                   //
                }
            }        //监听回调
            private void onCall(IAsyncResult ar)
            {
                allDone.Set();
                Socket serverSoc = (Socket)ar.AsyncState;
                Socket clent = serverSoc.EndAccept(ar);
                try
                {
                    if (serverSoc != null)
                    {
                        byte[] comes = new byte[1024];
                        EndPoint enp = clent.RemoteEndPoint;
                        serverSoc.BeginAccept(new AsyncCallback(onCall), serverSoc);
                        while (true)
                        {
                            int re = clent.Receive(comes, comes.Length, 0);
                            clent.Send(Encoding.ASCII.GetBytes("8"));
                            TCPParameter parm = new TCPParameter();
                            parm.Package = Encoding.UTF8.GetString(comes, 0, re).ToString().Trim();
                            parm.IpAddress = clent.RemoteEndPoint.ToString();
                            if (parm.Package.Length != 0)
                            {
                                Receive(parm.Package, parm.IpAddress);
                            }
                        }
                    }
                }
                catch (SocketException ex)
                {
                   //
                }
            }        //处理解析数据
            private void Receive(string msg, string ip)
            {
               //
            }        #endregion        #region 关闭与退出        //窗体关闭
            private void TcpServer_FormClosing(object sender, FormClosingEventArgs e)
            {
                if (mythread != null)
                {
                    mythread.Interrupt();
                    mythread.Abort();
                    GC.Collect();
                }
            }        #endregion
        }
    }
    http://blog.csdn.net/fengyarongaa/article/details/6631953
      

  14.   

    网站是不会让你控制socket的,你要想做到这效果,如果是windows操作系统的,需要开发一个后台服务程序,在服务程序里管理你自己的socket,web可以通过本地socket再跟你的服务程序通信。
      

  15.   

    如果你只是要来个用户就把该拥护记录 那么你还是用 Application  来做比较好的。这个在你的网站运行期间Application 会一直存在的。Cookie 保存在用户的客户端,而 Application 保存在服务器了 会一直存在  你可以查查Application的用法。对你会有帮助的。非常建议你使用Application
      

  16.   

    16楼已经给出答案了,楼主还是稍微了解一下ASP.NET应用的声明周期吧。MSDN:http://msdn.microsoft.com/zh-cn/library/ms227435(v=vs.80).aspx
      

  17.   

     private void Page_Loaded(object sender, RoutedEventArgs e)
            {
                while (true)
                {
                    Page_Loaded(sender,e);
                }
            }
      

  18.   

    Topshelf 我没有找到比较好的中文材料 ,英文看不懂依赖缓存 没有用过
    Web程序不能控制 socket吗?
      

  19.   

    依赖缓存 没有用过
    Web程序不能控制 socket吗?
      

  20.   

    Topshelf 我搜了下 没有找到中文材料 英文看不懂
      

  21.   

    这个网页能显示出来??没完没了的load
      

  22.   


      protected void Application_Start(object sender, EventArgs e)
            {
                Thread ti = new Thread(test);
                ti.Start();      
            } private void test()
            {
                int i = 1;
                while (true)
                {
                    //do some thing                i++;               
                    Thread.Sleep(100);            }
            }
      

  23.   

    当掉应该不会,CPU到百分之多少的一定程度就不会网上升了
      

  24.   

    想不影响其它用户,那只能把方法写到JS客户端中去了,。
     你可以判断一下登陆用户或COKIES什么的,。然后后台把一个JS循环方法写到公有的字符串中,。
     前台aspx页面引用这个字符串。,
    这样的话,是你需要的效果吧,。,。
    ---------
     没做测试,也不想做这样的测试,。
    不能确定肯定能用。,
      

  25.   

    自己建一个Windows服务,就可以实现的需求了~
      

  26.   

    是否可以尝试下quartz.net任务调度计划
      

  27.   

    for(int i = 0;i<=0;i--)
    {}
      

  28.   

     此贴要火~  
     你可以写个服务 或者跑个应用程序在上面~(就是 window应用程序~ 加个时间间隔 多长时间跑一次 太快了 是不太好)
      

  29.   

    果断WINDOWS服务
    并且每隔多少毫秒休眠一次以免CPU占用过高 
      

  30.   

    这个容易啊,for(int i=0:i<=20亿;i++)
    {
       记得休息一秒,
       然后运行你的方法,事件。
    }
      

  31.   

    新线程+while(true){},如果需要等待,就sleep线程
      

  32.   

    如果是死循环,那么你自己在Global文件中Application_Begin时创建一个线程,然后把这个线程的优先级尽量的调低,这样你的死循环既可以很好的运行,也不会影响其它人访问你的网站。
      

  33.   

    用TIMER吧,定时轮询,死循环是肯定不敢用的,或者多线程是必须的
      

  34.   

    windows编程的消息机制就是一个死循环。这要求也没什么奇怪的,
    换个名字就好理解了
      

  35.   

    你是不是打算写一个监控或者预警?页面写成死循环会Timeout直接结束的。
    1、写成应用程序,在服务器上跑
    2、写成单个页面,在任何一台机器上(包括服务器),用windows自带的任务调度,每XX秒访问一次该页面。
      

  36.   

    对于你的问题 可以通过观察者模式+单例模式做一个生产者,也就是25楼说的自定义事件的方法。对外广播数据变化。有新的实例需要获取你轮询的信息的时候 只需要注册相应的事件即可。至于死循环,可以使用微软提供的任务并行机制。启用Task进行异步操作,降低性能损耗。简单例子如下。使用Task也可以通过其信号机制强制停止任务 可以达到你有一个人可以控制轮循的目的   #region Sample
            CancellationTokenSource cts = new CancellationTokenSource();//提供循环取消机制
            //启动任务
            public void StartLoop()
            {            CancellationToken ct = cts.Token;            var loopTask = Task.Factory.StartNew(() => LoopBody(ct), ct);//启动一个任务            Task.WaitAll(loopTask);//等待任务完成        }
            /制终止任务
            public void StopLoop()
            {
                cts.Cancel();//取消当前任务
            }        //任务行为
            private void LoopBody(CancellationToken ct)
            {
                while (true)
                {
                    //判断是否有强制退出任务的请求
                    if (ct.IsCancellationRequested)
                    {
                        ct.ThrowIfCancellationRequested();
                    }                //TODO:你的逻辑
                    //在这里抛出自定义事件
                }
            }
            #endregion
      

  37.   

    弄了个windows 服务,但是 没办法在web页面上对和服务进行交互啊
      

  38.   

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;namespace Test
    {
        public sealed class MyTest
        {
            private static readonly MyTest _instance = new MyTest();
            private Socket _socket;
            private SocketAsyncEventArgs _asyncArgs;
            private byte[] _buffer = new byte[1024];
            private byte[] _tempbuffer;
            /// <summary>
            /// 
            /// </summary>
            private MyTest()
            { }
            /// <summary>
            /// 单例入口
            /// </summary>
            public static readonly MyTest Instance
            {
                get { return _instance; }
            }
            /// <summary>
            /// 连接Socket(只调用一次)
            /// </summary>
            /// <param name="ip"></param>
            /// <param name="port"></param>
            public void Connect(string ip, int port)
            {
                this._asyncArgs = new SocketAsyncEventArgs();
                this._asyncArgs.SetBuffer(this._buffer, 0, this._buffer.Length);
                this._asyncArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_asyncArgs_Completed);
                this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                bool result = this._socket.ConnectAsync(this._asyncArgs);
                if (!result)
                {
                  bool result1=  this._socket.ReceiveAsync(this._asyncArgs);
                  if (!result1)
                  {
                      this.ProcessReceive(this._asyncArgs);
                  }
                }
            }
            /// <summary>
            /// Socket事件
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void _asyncArgs_Completed(object sender, SocketAsyncEventArgs e)
            {
                switch (e.LastOperation)
                {
                    case SocketAsyncOperation.Receive: this.ProcessReceive(e); break;
                    case SocketAsyncOperation.Connect: this.ProcessConected(e); break;
                    default: break;
                }
            }
            /// <summary>
            /// 处理连接事件
            /// </summary>
            /// <param name="e"></param>
            private void ProcessConected(SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success)
                {
                   bool result= this._socket.ReceiveAsync(e);
                   if (!result)
                   {
                       this.ProcessReceive(e);
                   }
                }
            }
            /// <summary>
            /// 处理接收
            /// </summary>
            /// <param name="e"></param>
            private void ProcessReceive(SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
                {
                    byte[] bs = new byte[e.BytesTransferred];
                    Buffer.BlockCopy(this._buffer, 0, bs, 0, bs.Length);
                    this._tempbuffer = bs;
                    bool result = this._socket.ReceiveAsync(e);
                    if (!result)
                    {
                        this.ProcessReceive(e);
                    }
                }
            }
            /// <summary>
            /// 获取接收的数据
            /// </summary>
            /// <returns></returns>
            public byte[] GetData()
            {
                return this._tempbuffer;
            }
        }
    }
    Socket 接收死循环,楼主自己判断该判断的条件
      

  39.   

    windows服务定时任务啊。。定时调用你的web服务
      

  40.   

    我的意思是 能够在web页面上  对这个循环 进行控制,比如修改某个参数,比如终止循环
      

  41.   

    我写了一个windows服务,但是不知道怎么从web页面上对这个windows服务进行操作
      

  42.   


    为何不考虑下这个? 不过要使用Task的话需要使用ContinueWith进行任务延续处理异常
      

  43.   

    用线程吧,一个线程执行逻辑,一个线程监控,发现它DOWN了,就再启动一个,至于重复使用一个实例,那是你实例对象未识别,每个实例中定义一个GUID变量或加个开关,用于判定是否被调用。
      

  44.   

    for( ; ; )
    {
       //break 可以跳出来···
    }
      

  45.   

    我也倾向使用windows服务来做这个监听,但是不知道怎么从web页面上对这个windows服务进行操作,也就是管理员能够通过网站操作这个服务.25楼提出的 Task 这个没有研究过  在asp.net 中 能打到理想效果吗?
      

  46.   

    又不是Session_Start,怎么全和在线人数有关?