2011-12-23 46 views
2

我有一个方法可以在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(); 
     } 
    } 
} 
+4

+1为标题...搞笑:) :) :) – TheBoyan 2011-12-23 12:29:16

+0

但严重的是,CallCheckLogic()线程将Sleep()。是什么让你觉得它不?你遗漏了循环部分。 – 2011-12-23 12:32:47

+0

因为,我可以在我的网络监视器上看到正在使用“ChecksObject.CheckXLogic”方法检查的远程端口正在连续(几乎就像循环的方法一样),我添加了ChecksObject.Check1Logic方法(它们都很漂亮差不多相同) – Mike 2011-12-23 12:36:47

回答

2

我看不出这里有什么循环。您的CallCheckLogic方法被调用一次,然后结束并且线程停止执行。 也许在你的CheckXLogic之一有一个无限循环,所以你的线程似乎一直在工作,但我可以说这不可能有睡眠呼叫有问题。

尝试在Sleep之前和之后添加断点,您将知道是否执行了此行代码。