一段时间后停止代码

时间:2012-11-04 16:12:01

标签: c# sockets datetime loops

  

可能重复:
  Stop running the code after 15 seconds

我正在处理数据包嗅探器的代码,我只是想对它进行一些修改。现在我正在尝试编辑它,这样一旦我启动程序,它将只捕获数据包15秒。下面是拦截数据包的代码部分,你可以看到我正在处理Try / Catch / Throw,它就像一个循环。

        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();
            }
    }

您认为我可以如何修改此代码,以便在15秒后启动后停止它?我曾尝试使用DateTime,但它没有成功,我无法打破这个所谓的循环。

3 个答案:

答案 0 :(得分:0)

我认为您需要在特定时间说“15秒”之后测量时间并停止代码,StopWatch课程可以帮助您。

// 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实例你会做这样的事情。

TimeSpan timeGone = stopwatch.Elapsed;

为适应您的情景,您可以执行以下操作

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

一些有用的链接
MSDN StopWatch

注意:
我确信我已经给出了足够多的指示,任何人都可以通过这些基本方法来解决他的问题,也请检查我对其他方法的评论。

答案 1 :(得分:0)

您可以使用

System.Threading.Thread.Sleep(15000);

并将代码放在其后面。代码将在定义的延迟后执行。

祝你好运

答案 2 :(得分:0)

鉴于您的代码使用单独的线程来完成实际工作,您可以使用相当少量的代码进行设置:

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static YourSnifferClass sniffer = new YourSnifferClass();
        static AutoResetEvent done_event = new AutoResetEvent(false);

        static void Main(string[] args)
        {           
            sniffer.Start();

            // Wait for 15 seconds or until the handle is set (if you had a
            // Stopped event on your sniffer, you could set this wait handle
            // there: done_event.Set()
            done_event.WaitOne(TimeSpan.FromSeconds(15));

            // stop the sniffer
            sniffer.Stop();
        }
    }
}

希望有所帮助。