我有一个大问题,但可能它对我来说很重要:)。 “terminal.Bind(客户端);”如果IP不好,此行会导致我的程序挂起。我希望在5s工作后停止这个程序,因为如果IP在10s后错误,所有程序都挂起.. :(
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();
}
}
}
答案 0 :(得分:2)
你可以在一个线程中启动Bind,并启动一个计时器,如果线程需要X秒太长时间才能完成,你可以杀死线程或你的应用程序,无论你选择哪一个。
答案 1 :(得分:2)
尝试将调用包装在try catch中(假设抛出了一些异常):
try
{
terminal.Bind(client);
}
catch(Exception ex)
{
return;
}
答案 2 :(得分:1)
您可以使用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();
}
}
}
答案 3 :(得分:0)
我建议将网络内容放入第二个线程,然后可能会被主线程中止。
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();
}
}