1

可能重复:
15 秒后停止运行代码

我正在处理数据包嗅探器的代码,我只想对其进行一些修改。现在我正在尝试编辑它,以便一旦我启动程序,它只会捕获 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 但它没有成功,我无法打破这个所谓的循环。

4

3 回答 3

0

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.

于 2012-11-04T16:29:25.940 回答
0

You could use

System.Threading.Thread.Sleep(15000);

and put the code after it. the code will be executed after the defined delay.

Good Luck

于 2012-11-04T16:30:30.167 回答
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();
        }
    }
}

希望有帮助。

于 2012-11-04T17:04:40.560 回答