c#如何在一定时间后停止程序
本文关键字:程序 定时间 | 更新日期: 2023-09-27 18:19:04
我有一个大问题,但可能它只对我大:)。"terminal.Bind(client);"如果IP错误,这一行会导致我的程序挂起。我想在5秒后停止这个程序,因为如果IP在10秒后出错,所有程序都会挂起。(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rebex.TerminalEmulation;
using Rebex.Security;
using Rebex.Net;
namespace Routers_info_v._1
{
class Program
{
static void Main(string[] args)
{
Telnet client = new Telnet("192.168.1.1");
VirtualTerminal terminal = new VirtualTerminal(80, 25);
terminal.Bind(client);
terminal.SendToServer("pass'r");
terminal.SendToServer("sys ver'r");
TerminalState state;
do
{
state = terminal.Process(2000);
} while (state == TerminalState.DataReceived);
terminal.Save("terminal.txt", TerminalCaptureFormat.Text, TerminalCaptureOptions.DoNotHideCursor);
terminal.Unbind();
terminal.Dispose();
}
}
}
尝试在Try catch中包装调用(假设抛出了一些异常):
try
{
terminal.Bind(client);
}
catch(Exception ex)
{
return;
}
您可以在线程中启动Bind,并启动计时器,如果线程需要X秒才能完成,您可以终止线程或您的应用程序,根据您的选择。
您可以使用Task.Wait。这里有一个小的模拟操作,它将花费10秒,你等待它5秒完成:)
using System;
using System.Linq;
using System.Data.Linq;
using System.Data;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class VirtualTerminal
{
public VirtualTerminal(int a, int b) { }
public bool Bind() { System.Threading.Thread.Sleep(10000); return true; }
}
class Program
{
static void Main(string[] args)
{
VirtualTerminal terminal = new VirtualTerminal(80, 25);
Func<bool> func = () => terminal.Bind() ;
Task<bool> task = new Task<bool>(func);
task.Start();
if (task.Wait(5*1000))
{
// you got connected
}
else
{
//failed to connect
}
Console.ReadLine();
}
}
}
我建议把网络的东西放到第二个线程中,然后主线程可能会中止。
class Program {
static void Main(string[] args) {
Thread thread = new Thread(threadFunc);
thread.Start();
Stopwatch watch = new Stopwatch();
watch.Start();
while (watch.ElapsedMilliseconds < 5000 && thread.IsAlive)
;
if (!thread.IsAlive) {
thread.Abort();
Console.WriteLine("Unable to connect");
}
}
private static void threadFunc() {
Telnet client = new Telnet("192.168.1.1");
VirtualTerminal terminal = new VirtualTerminal(80, 25);
terminal.Bind(client);
// ...
terminal.Dispose();
}
}