我有一个在C#中创建一个运行方法的线程的方法(CallCheckLogic - 如下所示)虽然我已经指定了睡眠(Thread.Sleep(60000);)方法(例如ChecksObject.Check1Logic( ))保持循环,就像忽略睡眠线程方法一样。这对我来说没有逻辑意义,是否有人能够解释为什么会发生这种行为?
预期结果:创建一个新线程,调用CallCheckLogic方法,该方法本身调用ChecksObject.Check1Logic>> ChecksObject.Check7Logic然后是Thread.Sleep(60000);被调用,导致线程休眠60秒,然后运行循环并再次运行CallCheckLogic。
private void StartCheckerThread()
{
Thread t = new Thread(o =>{CallCheckLogic();});t.Start();
running = true;
}
public void CallCheckLogic()
{
Checks ChecksObject = new Checks();
ChecksObject.Check1Logic();
ChecksObject.Check2Logic();
ChecksObject.Check3Logic();
ChecksObject.Check4Logic();
ChecksObject.Check5Logic();
ChecksObject.Check6Logic();
ChecksObject.Check7Logic();
// This method / delegate parses the outfile of "temp" or rather the results of the tests and turns on / off the appropriate light on the GUI
LightControlDelegate d1 = new LightControlDelegate(lightControl);
this.BeginInvoke(d1);
Thread.Sleep(60000);
//LoopPorts();
}
ChecksObject.Check1Logic方法:
public void Check1Logic()
{
// clean up time!
File.Create("temp").Dispose();
// lets grabs the info from the config!
var lines = File.ReadAllLines("probe_settings.ini");
var dictionary = lines.Zip(lines.Skip(1), (a, b) => new { Key = a, Value = b })
.Where(l => l.Key.StartsWith("#"))
.ToDictionary(l => l.Key, l => l.Value);
// lets define variables and convert the string in the dictionary to int for the sock.connection method!
int portno1;
int.TryParse(dictionary["#PortNo1"], out portno1);
// Convert hostname to IP, performance issue when using an invalid port on a hostname using the TcpClient class!
IPAddress[] addresslist = Dns.GetHostAddresses(hostname2);
foreach (IPAddress theaddress in addresslist)
{
// Attempt to create socket and connect to specified port on host
TcpClient tcP = new System.Net.Sockets.TcpClient();
try
{
tcP.ReceiveTimeout = 1;
tcP.SendTimeout = 1;
tcP.Connect(theaddress, portno1);
tcP.Close();
StreamWriter sw = File.AppendText("temp");
sw.Flush();
sw.WriteLine("Check1=Success");
sw.Close();
}
catch
{
StreamWriter sw = File.AppendText("temp");
sw.WriteLine("Check1=Fail");
sw.Close();
}
}
}
答案 0 :(得分:2)
我在这里看不到任何循环。调用CallCheckLogic
方法,然后结束,线程停止执行。
也许你的一个CheckXLogic
中存在无限循环,所以你的线程似乎一直在工作,但我可以说睡眠呼叫不太可能存在问题。
尝试在Sleep
之前和之后添加断点,您将知道是否执行了这行代码。