可能重复:
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 但它没有成功,我无法打破这个所谓的循环。