C# 在一段时间后停止代码
可能重复:C# 在一段时间后停止代码,c#,sockets,datetime,loops,C#,Sockets,Datetime,Loops,可能重复: 我正在处理一个包嗅探器的代码,我只想对它做一些修改。现在我正在尝试编辑它,这样一旦我启动程序,它将只捕获数据包15秒。下面是截取数据包的代码部分,正如您所看到的,我正在处理Try/Catch/Throw,它就像一个循环 public void Start() { if (m_Monitor == null) { try {
我正在处理一个包嗅探器的代码,我只想对它做一些修改。现在我正在尝试编辑它,这样一旦我启动程序,它将只捕获数据包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();
}
}
public void Start(){
如果(m_Monitor==null)
{
尝试
{
m_Monitor=新套接字(AddressFamily.InterNetwork、SocketType.Raw、ProtocolType.IP);
m_Monitor.Bind(新的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);
}
接住
{
m_Monitor=null;
抛出新的SocketException();
}
}
}
///
///停止在指定接口上侦听。
///
公共停车场(){
如果(m_监视器!=null){
m_Monitor.Close();
m_Monitor=null;
}
}
///
///当套接字截获IP数据包时调用。
///
///异步结果。
///
私有void OnReceive(IAsyncResult ar){
尝试
{
int received=m_Monitor.EndReceive(ar);
尝试
{
如果(m_监视器!=null)
{
字节[]数据包=新字节[已接收];
复制(缓冲区,0,数据包,0,接收);
OnNewPacket(新数据包(数据包));
}
}
捕获{}//无效数据包;忽略
m_Monitor.BeginReceive(Buffer,0,Buffer.Length,SocketFlags.None,new AsyncCallback(this.OnReceive),null);
}
接住
{
停止();
}
}
您认为我如何修改此代码,使其在15秒后启动时停止?我曾尝试使用DateTime,但没有成功,我无法打破这种所谓的循环。我认为您需要测量时间,并在特定时间后停止代码,比如说“15秒”
秒表类可以帮您解决问题
// 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
您可以这样做
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
秒表秒表=新秒表();
时间跨度时间过去了;
//使用TimeSpan构造函数指定:
// ... 天,小时,分钟,秒,毫秒。
// ... 返回的TimeSpan具有这些值。
TimeSpan RequiredTimeLine=新的TimeSpan(0,0,0,15,0)//设置为15秒
While(timeGone.Seconds
一些有用的链接
注意:
我确信我已经给出了足够多的建议,任何人都可以通过这些基本方法来解决问题,同时也请检查我的评论,以了解其他方法。您可以使用
System.Threading.Thread.Sleep(15000);
然后把代码放在后面。代码将在定义的延迟后执行
祝您好运鉴于您的代码使用一个单独的线程来完成实际工作,您可以使用少量代码进行设置:
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();
}
}
}
希望这能有所帮助。这是一个扩展问题。。。我被要求打开另一个问题…@iSi你能添加一些实际调用Start()
的代码吗这不是我的意图。。。这只会使线程处于睡眠状态15秒,然后无论如何都会运行它。。。我需要启动程序,然后让它运行15秒,然后让它自动停止…@iSi检查我的建议,然后让我know@dotNetSoldier我不明白你的意思。。。你想让我写一个条件来检查经过的时间,如果超过15秒,它就会停止,对吗?嗯,我想我的程序有一些基本的问题,因为我在尝试/捕获代码之间迷失了方向,不知道把你的代码放在哪里…@iSi我现在在微笑,当我们的思想因为这个问题而被占用太多的时候,我会给你一些建议。@dotNetSoldier非常感谢man@iSi我再次检查了你的代码,但找不到你在这里发布的内容,如果time==15秒,那么使用events raiseonStop
可以调用stop方法。