一段时间后停止代码 [英] Stop the code after a time period

查看:138
本文介绍了一段时间后停止代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

15秒后停止运行代码


我正在处理数据包嗅探器的代码,我只想对其进行一些修改。现在我正在编辑它,所以一旦启动程序,它将只捕获数据包15秒。以下是截取数据包的代码部分,您可以看到我正在处理Try / Catch / Throw,它的工作原理就像循环。

 code> public void Start(){
if(m_Monitor == null)
{

try
{

m_Monitor = new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.IP);
m_Monitor.Bind(new IPEndPoint(IP,0));
m_Monitor.IOControl(SIO_RCVALL,BitConverter.GetBytes((int)1),null);
m_Monitor.BeginReceive(m_Buffer,0,m_Buffer.Length,SocketFlags.None,new AsyncCallback(this.OnReceive),null);
}
catch
{
m_Monitor = null;
throw new SocketException();
}
}
}
///< summary>
///停止侦听指定的接口。
///< / summary>
public void Stop(){
if(m_Monitor!= null){
m_Monitor.Close();
m_Monitor = null;
}
}
///< summary>
///当套接字拦截IP数据包时调用。
///< / summary>
///< param name =ar>异步结果< / param>
///
private void OnReceive(IAsyncResult ar){
try
{
int received = m_Monitor.EndReceive(ar);
try
{
if(m_Monitor!= null)
{
byte [] packet = new byte [received];
Array.Copy(Buffer,0,packet,0,received);
OnNewPacket(new Packet(packet));
}
}
catch {} // invalid packet;忽略
m_Monitor.BeginReceive(Buffer,0,Buffer.Length,SocketFlags.None,new AsyncCallback(this.OnReceive),null);
}
catch
{
Stop();
}
}

你觉得我可以修改这段代码,以便例如在15秒后才能停止一次?我试图使用DateTime,但并不成功,我无法打破这个所谓的循环。

解决方案

我想你需要测量时间,并在特定时间后停止代码说15秒, StopWatch class可以帮助你。

  //创建新的秒表实例
秒表秒表=新的秒表();
//开始秒表
stopwatch.Start();
//停止秒表
stopwatch.Stop();
//写入结果
Console.WriteLine(Time elapsed:{0},秒表。
//如果超过15秒,您可以检查Elapsed属性
//然后停止代码

已经过的属性返回TimeSpan 实例,你会做这样的事情。

  TimeSpan timeGone =秒表。 

为了适应您的方案,您可以做这样的事情

 秒表秒表=新秒表(); 
TimeSpan timeGone;
//使用TimeSpan构造函数指定:
// ...天,小时,分钟,秒,毫秒。
// ...返回的TimeSpan有这些值。
TimeSpan RequiredTimeLine = new TimeSpan(0,0,0,15,0); //设置为15秒

While(timeGone.Seconds< RequiredTimeLine.Seconds)
{
stopwatch.Start();
Start();
timeGone =秒表。
}
Stop(); //您将停止收听的方法

一些有用的链接

给了足够的指针,任何人都可以通过这些基本方法来解决他的问题,请同时检查我的评论另一种方法。


Possible Duplicate:
Stop running the code after 15 seconds

I am dealing with the code of a packet sniffer and I just want to make some modifications to it. Now I am trying to edit it so that once I start the program, it will only capture the packets for 15 seconds. Below is the part of code which intercepts the packets and as you can see I am dealing with Try/Catch/Throw and it works like a loop.

        public void Start() {
            if (m_Monitor == null)
            {

                try
                {

                    m_Monitor = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                    m_Monitor.Bind(new IPEndPoint(IP, 0));
                    m_Monitor.IOControl(SIO_RCVALL, BitConverter.GetBytes((int)1), null);
                    m_Monitor.BeginReceive(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
                }
                catch
                {
                    m_Monitor = null;
                    throw new SocketException();
                }
            }
    }
    /// <summary>
    /// Stops listening on the specified interface.
    /// </summary>
    public void Stop() {
        if (m_Monitor != null) {
            m_Monitor.Close();
            m_Monitor = null;
        }
    }
    /// <summary>
    /// Called when the socket intercepts an IP packet.
    /// </summary>
    /// <param name="ar">The asynchronous result.</param>
    /// 
    private void OnReceive(IAsyncResult ar) {
            try
            {
                int received = m_Monitor.EndReceive(ar);
                try
                {
                    if (m_Monitor != null)
                    {
                        byte[] packet = new byte[received];
                        Array.Copy(Buffer, 0, packet, 0, received);
                        OnNewPacket(new Packet(packet));
                    }
                }
                catch { } // invalid packet; ignore
                m_Monitor.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
            }
            catch
            {
                Stop();
            }
    }

How do you think I can modify this code so that it will be stopped once started after 15 seconds for instance? I have tried to use DateTime but it was not successfull and I couldn't kind of break this so-called loop.

解决方案

I think you need to measure time and stop the code after particular time say "15 seconds" ,StopWatch class can help you out.

// Create new stopwatch instance
Stopwatch stopwatch = new Stopwatch();
// start stopwatch
stopwatch.Start();
// Stop the stopwatch
stopwatch.Stop();
// Write result
Console.WriteLine("Time elapsed: {0}",stopwatch.Elapsed);
// you can check for Elapsed property when its greater than 15 seconds 
//then stop the code

Elapsed property returns TimeSpan instance you would do something like this.

TimeSpan timeGone = stopwatch.Elapsed;

To fit your scenario you can do something like this

Stopwatch stopwatch = new Stopwatch();
TimeSpan timeGone;
// Use TimeSpan constructor to specify:
// ... Days, hours, minutes, seconds, milliseconds.
// ... The TimeSpan returned has those values.
TimeSpan RequiredTimeLine = new TimeSpan(0, 0, 0, 15, 0);//set to 15 sec

While ( timeGone.Seconds < RequiredTimeLine.Seconds )
{
    stopwatch.Start();
    Start();
    timeGone = stopwatch.Elapsed;
}
Stop();//your method which will stop listening

Some useful links
MSDN StopWatch

Note:
Im' sure that i have given enough pointers that anyone can sort his problem through these basic approach ,kindly also check my comments for another approach.

这篇关于一段时间后停止代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆