怎么写死循环程序
我想问一个问题 我想放一段死循环程序到 网站里面去
要怎么弄才能达到以下条件
1.不影响其他使用者
2.不需要有人去点击页面触发
3.网站运行周期内 ,这段程序都要运行
4.特定网站使用者, 可以影响,操作这段程序
[解决办法]
线程中
while(true)
{
}
[解决办法]
发现你的4条要求 我错了
[解决办法]
看样子像是一个游戏的数据读取,显示在网页上是吗。。
[解决办法]
global.asax 中写 可以实现你的要求
[解决办法]
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 }}
[解决办法]
你的要求不应该和死循环挂钩,可尝试缓存依赖之类的...
[解决办法]
用定时器去做
[解决办法]
#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
[解决办法]
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 接收死循环,楼主自己判断该判断的条件
[解决办法]
windows服务定时任务啊。。定时调用你的web服务。。。
[解决办法]
在一些行业的软件中,死循环是有必要的,例如医疗器材,金融的支持系统
[解决办法]